I have a form to display where only one input box must be pre filled with values that come from a parent component. The input box must also be made un-editable. Here is the code for the HTML and the TS file for the same being defined in a very crude form form.
triggerform.component.html:
{{triggerID}}<!-- shows the fetched value -->
<form #userForm="ngForm">
<input type="text" name="triggerID" [(ngModel)]="userData.triggerID"><br><br>
<button type="submit">Submit Changes</button>
</form>
triggerform.component.ts:
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-triggerform',
templateUrl: './triggerform.component.html',
styleUrls: ['./triggerform.component.css'],
})
export class TriggerformComponent implements OnInit {
@Input() parentEmailID!: string;
@Input() triggerID!: any;
@Input() triggerAssignedTo!: string;
@Input() isActive!: boolean;
userData={
triggerID: this.triggerID
}
constructor() {}
ngOnInit(): void {}
}
But still my input box appears empty.Can anyone please help in getting this done?
CodePudding user response:
You could use the ngOnChanges lifecycle hook for that. This method will be triggered everytime your Input() decorator receives a value from the parent. You will have something like:
export class TriggerformComponent implements OnInit, OnChanges{
@Input() triggerID!: any;
userData = {
triggerID: '',
};
ngOnChanges() {
this.userData.triggerID = this.triggerID;
}
}
Although since you have more than one input, this will be triggered every time any of yours Input() receives a value and that's not good. So you can use a set method for that, something like:
export class TriggerformComponent implements OnInit{
@Input() set triggerID(id: any) {
this.userData.triggerID = id;
}
userData = {
triggerID: '',
};
}
The triggerID inside userData will be initialized only when the triggerID Input() receives a value and updated every time a new value is passed from the parent to the child.
I'm not sure if I understood the uneditable value part, if you mean like a disabled input, you can just add the disabled attribute in your input tag
<input type="text" name="triggerID" [(ngModel)]="userData.triggerID" disabled><br><br>