Angular 8+ two way binding textarea in reactive forms - html

I want to bind my textarea input.
HTML:
<form [formGroup]="formGroup">
<custom-element formControlName="firstName"</custom-element>
<textarea formControlName="question" rows="6" placehoder"some text"></textarea>
</form>
TS:
formGroup = this.formBuilder.group({
firstName: [{value: null, disabled: true}],
question:[null]
});
get firstNameControl(): AbstractControl {return this. formGroup.get('firstName');}
get questionControl(): AbstractControl {return this. formGroup.get('question');}
dosomething(): void {
// fill firstname form api work fine
// I can read the value with this.firstNameControl.value
}
Tried to bind textarea but no working solution yet.
message: string;
this.questionControl.valueChanges.subscribe(
val => {
this.message= val;
console.log('questiontext' + this.message);
}
);
or
this.questionControl.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
tap(message => this.message = message),
tap(data => console.log(data))
).subscribe();
if I add [(ngModel)]="message" to the textarea and remove formCotroleName it works.
But than you are combining two way of presenting the form which is not the way to go.
How can I two way bind a textarea or other form element with reactive forms?

Related

How to force validation for disabled property?

I have a form element as follows:
<input type="text" id="country" formControlName="Country" />
I have form group as follows:
this.myForm = this.formbuilder.group({
'Country': [{ value: this.user.Country, disabled: this.SomeProperty===true}, [Validators.required]],
});
When it is disabled when this.SomeProperty is true, required validator does not work at all and Save button is enabled.
<button type="submit" [disabled]="!myForm.valid">Save</button>
Is there anyway to force validation for disabled attribute?
The reason the required property can be null is because of some data issue or data got migrated from different source without the required values which is beyond my control.
Hmmm.. Generally, Angular Reactive Forms will not trigger validators for disabled form fields.
I can suggest two ways for you to get around this situation:
1) Writing a custom validator on your FormGroup to manually check the values for each individual Form Control.
this.myForm = this.formbuilder.group({
'Country': [{ value: this.user.Country, disabled: this.SomeProperty===true}, [Validators.required]],
// other FormControls
}, { validator: GroupValidator.checkEveryField() });
Then, create a new Validator class that checks for an empty Country FormControl. If it is empty, it will return the validation error.
import { AbstractControl } from '#angular/forms';
export class GroupValidator {
static checkEveryField(control: AbstractControl) {
const { Country } = control.value;
if (!Country) {
return { 'invalidCountry': true };
} else {
return null;
}
}
}
2) Writing a method that checks the values of the incoming data before you patch the values to your FormGroup.
this.someService.getData().subscribe(response => {
if (!response.user.Country) {
// trigger invalid validation response
} else {
this.myForm.patchVaue(response.user);
}
});

using angular, express and mongoDB: How to format date in input element without breaking NgModel?

I have an deadlineDate (Date format) property in my mongoDB. In my component.html I have an input field where I want the user to be able to change the deadlineDate.
when opening the component.html the full date is shown in the input textfield
<label>project deadline:
<input [(ngModel)]="project.deadlineDate"
placeholder="{{project.deadlineDate | date }}"
type="text"
onfocus="(this.type='date')"
onblur="(this.type='text')" />
</label>
returns on opening html: 2019-02-20T00:00:00.000Z in my input field. I want it to return 20-02-2019
any ideas on how I can format this? Suggestions on how to make this more userfriendly/ -usable/ -readable are also welcome ofcourse.-
component.ts:
ngOnInit(): void {
this.getProject();
};
getProject(): void {
const id = this.route.snapshot.paramMap.get('id');
this.projectService.getProject(id)
.subscribe(project => this.project = project);
};
service.ts
getProject(id: string): Observable<Project> {
const url = `${this.backendUrl}/project/${id}`;
return this.http.get<Project>(url)
.pipe(
map(project => project[0]),
tap(res => console.log(res)),
catchError(this.handleError<Project>(`getProject id=${id}`))
);
};

How to change JSON data through textboxes and buttons in a ReactJS?

I just started learning react.
Please see code in codepen link below.
When you press the edit button, the field in the table is changed to a textbox.
And that's what I want.
I wanna give Click on the edit button again.
How to replace the value of the data in JSON data?
Thanks so much for the help.
let UsersData = [
{Name: 'AAA',Last:"1111"},
{Name: 'BBBB',Last:"222"},
]
constructor(props) {
super(props)
this.state={
Editing:false,
}
this.toggleEditing = this.toggleEditing.bind(this)}
toggleEditing() {
let Editing = !this.state.Editing
this.setState(
{Editing: Editing}
)}
FULL CODE IN CODEPEN
Codepen https://codepen.io/StCrownClown/pen/MEQPzP?editors=0010
To change your JSON data first you need to get the user input through your TextInput component, to do that you need to define a value and an onChange props to store the value of the input in your state. Given that your input is a custom component I'll pass those props as props.
Like this:
class TextInput extends React.Component {
render() {
const {value, onChange, name} = this.props
return (
<td>
<input type="text"
value={value} // to display the value
onChange={onChange} // to store the value on the state
name={name} // to use use the name as a property of the state
/>
</td>
)
}
}
Then in your TableRow component state, you need to:
Save those value and handle their changes:
this.state = {
Editing:false,
// from props to show their current value
name : this.props.data.Name
last: this.props.data.Last
}
// to handle changes
onChange(event){
this.setState({
[event.target.name] : event.target.value
})
}
and pass the above mentioned props to the TextInput:
<TextInput value={this.state.name} name="name" onChange={this.onChange}></TextInput>
<TextInput value={this.state.last} name="last" onChange={this.onChange} ></TextInput>
To show those values to the user when to Editing is false you need to:
Defined a state for your Table component so it re-renders with the changes and a function that changes that state when the user is done editing:
this.state = {
UsersData: UsersData
}
saveChanges({key, name, last}){
// key: unique identifier to change the correct value in the array
// name: new Name
// last: new Last
this.setState(prevState => ({
UsersData: prevState.UsersData.map(data => {
if(data.Name === key) return { Name: name, Last: last }
return data
})
}))
}
Finally, pass that function to the TableRow component:
const rows = []
// now the loop is from the UsersData in the component state to see the changes
this.state.UsersData.forEach((data) => {
rows.push (
<TableRow
key={data.Name}
saveChanges={this.saveChanges}
data={data}
/>
)
})
and call the saveChanges function in the TableRow component when the Done button is clicked:
saveChanges(){
const {name , last} = this.state
this.toggleEditing()
this.props.saveChanges({
key: this.props.data.Name,
name,
last
})
}
<button onClick={this.saveChanges} >Done</button>
You can check the full code here.

Binding ngModel to complex data

For some time I have been researching if, and how to bind complex model to ngModel. There are articles showing how it can be done for simple data (e.g. string) such as this. But what I want to do is more complex. Let's say that I have a class:
export class MyCoordinates {
longitude: number;
latitude: number;
}
Now I am going to use it in multiple places around the application, so I want to encapsulate it into a component:
<coordinates-form></coordinates-form>
I would also like to pass this model to the component using ngModel to take advantage of things like angular forms but was unsuccessful thus far. Here is an example:
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" [(ngModel)]="model.name" name="name">
</div>
<div class="form-group">
<label for="coordinates">Coordinates</label>
<coordinates-form [(ngModel)]="model.coordinates" name="coordinates"></coordinates-form>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
Is actually possible to do it this way or is my approach simply wrong? For now I have settled on using component with normal input and emitting event on change but I feel like it will get messy pretty fast.
import {
Component,
Optional,
Inject,
Input,
ViewChild,
} from '#angular/core';
import {
NgModel,
NG_VALUE_ACCESSOR,
} from '#angular/forms';
import { ValueAccessorBase } from '../Base/value-accessor';
import { MyCoordinates } from "app/Models/Coordinates";
#Component({
selector: 'coordinates-form',
template: `
<div>
<label>longitude</label>
<input
type="number"
[(ngModel)]="value.longitude"
/>
<label>latitude</label>
<input
type="number"
[(ngModel)]="value.latitude"
/>
</div>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: CoordinatesFormComponent,
multi: true,
}],
})
export class CoordinatesFormComponent extends ValueAccessorBase<MyCoordinates> {
#ViewChild(NgModel) model: NgModel;
constructor() {
super();
}
}
ValueAccessorBase:
import {ControlValueAccessor} from '#angular/forms';
export abstract class ValueAccessorBase<T> implements ControlValueAccessor {
private innerValue: T;
private changed = new Array<(value: T) => void>();
private touched = new Array<() => void>();
get value(): T {
return this.innerValue;
}
set value(value: T) {
if (this.innerValue !== value) {
this.innerValue = value;
this.changed.forEach(f => f(value));
}
}
writeValue(value: T) {
this.innerValue = value;
}
registerOnChange(fn: (value: T) => void) {
this.changed.push(fn);
}
registerOnTouched(fn: () => void) {
this.touched.push(fn);
}
touch() {
this.touched.forEach(f => f());
}
}
Usage:
<form #form="ngForm" (ngSubmit)="onSubmit(form.value)">
<coordinates-form
required
hexadecimal
name="coordinatesModel"
[(ngModel)]="coordinatesModel">
</coordinates-form>
<button type="Submit">Submit</button>
</form>
The error I am getting Cannot read property 'longitude' of undefined. For simple model, like string or number it works without a problem.
The value property is undefined at first.
To solve this issue you need to change your binding like:
[ngModel]="value?.longitude" (ngModelChange)="value.longitude = $event"
and change it for latitude as well
[ngModel]="value?.latitude" (ngModelChange)="value.latitude = $event"
Update
Just noticed you're running onChange event within settor so you need to change reference:
[ngModel]="value?.longitude" (ngModelChange)="handleInput('longitude', $event)"
[ngModel]="value?.latitude" (ngModelChange)="handleInput('latitude', $event)"
handleInput(prop, value) {
this.value[prop] = value;
this.value = { ...this.value };
}
Updated Plunker
Plunker Example with google map
Update 2
When you deal with custom form control you need to implement this interface:
export interface ControlValueAccessor {
/**
* Write a new value to the element.
*/
writeValue(obj: any): void;
/**
* Set the function to be called when the control receives a change event.
*/
registerOnChange(fn: any): void;
/**
* Set the function to be called when the control receives a touch event.
*/
registerOnTouched(fn: any): void;
/**
* This function is called when the control status changes to or from "DISABLED".
* Depending on the value, it will enable or disable the appropriate DOM element.
*
* #param isDisabled
*/
setDisabledState?(isDisabled: boolean): void;
}
Here is a minimal implementation:
export abstract class ValueAccessorBase<T> implements ControlValueAccessor {
// view => control
onChange = (value: T) => {};
onTouched = () => {};
writeValue(value: T) {
// control -> view
}
registerOnChange(fn: (_: any) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
}
It will work for any type of value. Just implement it for your case.
You do not need here array like (see update Plunker)
private changed = new Array<(value: T) => void>();
When component gets new value it will run writeValue where you need to update some value that will be used in your custom template. In your example you are updating value property which is used together with ngModel in template.
In my example i am drawing new marker.
DefaultValueAccessor just updates value property https://github.com/angular/angular/blob/4.2.0-rc.0/packages/forms/src/directives/default_value_accessor.ts#L76
Datepicker in angular2 material is setting inner value as you do https://github.com/angular/material2/blob/123d7eced4b4f808fc03c945504d68280752d533/src/lib/datepicker/datepicker-input.ts#L202
When you need to propagate changes to AbstractControl you have to call onChange method which you registered in registerOnChange.
I wrote this.value = { ...this.value }; because it is just
this.value = Object.assign({}, this.value)
it will call setter where you call onChange method
Another way is calling onChange directly that is usually used
this.onChange(this.value);
Your example https://plnkr.co/edit/Q11HXhWKrndrA8Tjr6KH?p=preview
DefaultValueAccessor https://github.com/angular/angular/blob/4.2.0-rc.0/packages/forms/src/directives/default_value_accessor.ts#L88
Material2 https://github.com/angular/material2/blob/123d7eced4b4f808fc03c945504d68280752d533/src/lib/datepicker/datepicker-input.ts#L173
You can do anything you like inside custom component. It can have any template and any nested components. But you have to implement logic for ControlValueAccessor to do it working with angular form.
If you open some library such angular2 material or primeng you can find a lot of example how to implement such controls

How to reset ReactJS file input

I have file upload input:
<input onChange={this.getFile} id="fileUpload" type="file" className="upload"/>
And I handle upload this way:
getFile(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = (theFile) => {
var data = {
blob: theFile.target.result, name: file.name,
visitorId: this.props.socketio.visitorId
};
console.log(this.props.socketio);
this.props.socketio.emit('file-upload', data);
};
reader.readAsDataURL(file);
}
If I upload same file twice, then upload event is not fired. How can I fix that? For simple js code it was enough to do the following: this.value = null; in change handler. How can I do it with ReactJS?
I think you can just clear the input value like this :
e.target.value = null;
File input cannot be controlled, there is no React specific way to do that.
Edit For old browsers (<IE11), you can use one of the following techniques.
See http://jsbin.com/zurudemuma/1/edit?js,output (tested on IE10 & 9)
What worked for me was setting a key attribute to the file input, then when I needed to reset it I update the key attribute value:
functionThatResetsTheFileInput() {
let randomString = Math.random().toString(36);
this.setState({
theInputKey: randomString
});
}
render() {
return(
<div>
<input type="file"
key={this.state.theInputKey || '' } />
<button onClick={this.functionThatResetsTheFileInput()} />
</div>
)
}
That forces React to render the input again from scratch.
This work for me - ref={ref => this.fileInput = ref}
<input id="file_input_file" type="file" onChange={(e) => this._handleFileChange(e)} ref={ref=> this.fileInput = ref} />
then in my case once the file was uploaded to the server , I clear it by using the statement below
this.fileInput.value = "";
I do it by updating key inside my file input.
This will force a re-render and previously selected file will go away.
<input type="file" key={this.state.inputKey} />
Changing the state inputKey will re-render the component.
One way to change the inputKey will be to always set it to Date.now() on click of a button which is supposed to clear the field.
With every click onClick you can reset the input, so that even with the same file onChange will be triggered.
<input onChange={this.onChange} onClick={e => (e.target.value = null)} type="file" />
import React, { useRef } from "react";
export default function App() {
const ref = useRef();
const reset = () => {
ref.current.value = "";
};
return (
<>
<input type="file" ref={ref} />
<button onClick={reset}>reset</button>
</>
);
}
The following worked for me using React Hooks. This is done using what is known as a "controlled input". That means, the inputs are controlled by state, or their source of truth is state.
TL;DR Resetting the file input was a two-step process using both the useState() and useRef() hooks.
NOTE: I also included how I reset a text input in case anyone else was curious.
function CreatePost({ user }) {
const [content, setContent] = React.useState("");
const [image, setImage] = React.useState(null); //See Supporting Documentation #1
const imageInputRef = React.useRef(); //See Supporting Documentation #2
function handleSubmit(event) {
event.preventDefault(); //Stop the pesky default reload function
setContent(""); //Resets the value of the first input - See #1
//////START of File Input Reset
imageInputRef.current.value = "";//Resets the file name of the file input - See #2
setImage(null); //Resets the value of the file input - See #1
//////END of File Input Reset
}
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Add Post Content"
onChange={event => setContent(event.target.value)}
value={content} //Make this input's value, controlled by state
/>
<input
type="file"
onChange={event => setImage(event.target.files[0])} //See Supporting Doc #3
ref={imageInputRef} //Apply the ref to the input, now it's controlled - See #2
/>
<button type="submit">Submit Form</button>
</form>
</div>
)
};
Supporting Documentation:
useState Hook
Returns a stateful value, and a function to update it.
useRef Hook
If you pass a ref object to React, React will set its current property to the corresponding DOM node whenever that node changes.
Using files from web apps
If the user selects just one file, it is then only necessary to consider the first file of the list.
You can also include this in your input element if you know you are not going to be using the built-in file input value at all.
<input value={""} ... />
This way the value is always reset to the empty string on render and you don't have to include it awkwardly in an onChange function.
I know file input is always uncontrolled however the following code still works in my own porject, I can reset the input with no problems at all.
constructor(props) {
super(props);
this.state = {
selectedFile: undefined,
selectedFileName: undefined,
imageSrc: undefined,
value: ''
};
this.handleChange = this.handleChange.bind(this);
this.removeImage = this.removeImage.bind(this);
}
handleChange(event) {
if (event.target.files[0]) {
this.setState({
selectedFile: event.target.files[0],
selectedFileName: event.target.files[0].name,
imageSrc: window.URL.createObjectURL(event.target.files[0]),
value: event.target.value,
});
}
}
// Call this function to reset input
removeImage() {
this.setState({
selectedFile: undefined,
selectedFileName: undefined,
imageSrc: undefined,
value: ''
})
}
render() {
return (
<input type="file" value={this.state.value} onChange={this.handleChange} />
);
}
We can reset file input by using key = {this.state.fileInputKey} and initialsing fileInputKey to Date.now() in constructor state.
On file upload success , we need to again assign fileInputKey: Date.now(), so it will have different value than previous and it create new file input component on next render()
We can also do this manually by clicking button to clear/reset file Input
Below is the working code :
import React from "react";
import { Button } from "reactstrap";
class FileUpload extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
fileInputKey: Date.now(),
message: ""
};
this.handleClear = this.handleClear.bind(this);
this.onClickHandler = this.onClickHandler.bind(this);
this.onChangeHandler = this.onChangeHandler.bind(this);
}
onChangeHandler = event => {
this.setState({
selectedFile: event.target.files
});
};
onClickHandler = () => {
if (this.state.selectedFile === null) {
this.setState({
message: "Please select File"
});
return;
}
//axios POST req code to send file to server
{
/**
const data = new FormData()
data = this.state.selectedFile[0]
axios.post("http://localhost:8080/api/uploadFile/", data)
.then(res => {
if (res.status == 200) {
// upload success
}
})
.catch(err => {
//message upload failed
})
*/
}
//after upload to server processed
this.setState({
selectedFile: null,
fileInputKey: Date.now(),
message: "File Uploaded"
});
};
handleClear() {
this.setState({
selectedFile: null,
fileInputKey: Date.now(),
message: ""
});
}
render() {
return (
<div>
<input
type="file"
key={this.state.fileInputKey}
class="form-control"
onChange={this.onChangeHandler}
/>
<button
type="button"
class="btn btn-success btn-block"
onClick={this.onClickHandler}
>
Upload
</button>
<Button
type="button"
value="Clear"
data-test="clear"
onClick={this.handleClear}
>
{" "}
Clear{" "}
</Button>
<br />
<label>{this.state.message}</label>
</div>
);
}
}
export default FileUpload;
Here is my solution using redux form
class FileInput extends React.Component {
constructor() {
super();
this.deleteImage = this.deleteImage.bind(this);
}
deleteImage() {
// Just setting input ref value to null did not work well with redux form
// At the same time just calling on change with nothing didn't do the trick
// just using onChange does the change in redux form but if you try selecting
// the same image again it doesn't show in the preview cause the onChange of the
// input is not called since for the input the value is not changing
// but for redux form would be.
this.fileInput.value = null;
this.props.input.onChange();
}
render() {
const { input: { onChange, value }, accept, disabled, error } = this.props;
const { edited } = this.state;
return (
<div className="file-input-expanded">
{/* ref and on change are key properties here */}
<input
className="hidden"
type="file"
onChange={e => onChange(e.target.files[0])}
multiple={false}
accept={accept}
capture
ref={(input) => { this.fileInput = input; }}
disabled={disabled}
/>
{!value ?
{/* Add button */}
<Button
className="btn-link action"
type="button"
text="Add Image"
onPress={() => this.fileInput.click()}
disabled={disabled}
/>
:
<div className="file-input-container">
<div className="flex-row">
{/* Image preview */}
<img src={window.URL.createObjectURL(value)} alt="outbound MMS" />
<div className="flex-col mg-l-20">
{/* This button does de replacing */}
<Button
type="button"
className="btn-link mg-b-10"
text="Change Image"
onPress={() => this.fileInput.click()}
disabled={disabled}
/>
{/* This button is the one that does de deleting */}
<Button
type="button"
className="btn-link delete"
text="Delete Image"
onPress={this.deleteImage}
disabled={disabled}
/>
</div>
</div>
{error &&
<div className="error-message"> {error}</div>
}
</div>
}
</div>
);
}
}
FileInput.propTypes = {
input: object.isRequired,
accept: string,
disabled: bool,
error: string
};
FileInput.defaultProps = {
accept: '*',
};
export default FileInput;
In my case I had a functional component and after selecting a file it suppose to set the file name in the state so using any solution above was failing except the ref one which i fixed like this.
const fileUpload = props => {
const inputEl = useRef(null)
const onUpload = useCallback(e => {
uploadFile(fileDetails)
.then(res => {
inputEl.current.value = ''
})
.catch(err => {
inputEl.current.value = ''
})
})
return (
<input type='file' ref={inputEl} onChange={handleChange} />
<Button onClick={onUpload}>Upload</Button>
)
}
I recently got stumbled into this issue to reset the File type input field. I think it is still a milestone for most developers. So I thought I should share my solution.
Since we are listening to the onChange event to update the image file into some of our states, we will have our component rerendered once we set the state. In such case, we can specify the value of the input file as empty like value='' which will cause the input field to reset its value after each change of its value.
<input
type="file"
value=''
onChange={onChangeFnc}
/>