我有一個要顯示的表單,其中只有一個輸入框必須預先填充來自父組件的值。輸入框也必須不可編輯。這是 HTML 和 TS 檔案的代碼,它們以非常粗略的形式定義。
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 {}
}
但是我的輸入框仍然是空的。有人可以幫忙完成嗎?
uj5u.com熱心網友回復:
您可以為此使用 ngOnChanges 生命周期掛鉤。每當您的 Input() 裝飾器從父級接收到值時,都會觸發此方法。你會有類似的東西:
export class TriggerformComponent implements OnInit, OnChanges{
@Input() triggerID!: any;
userData = {
triggerID: '',
};
ngOnChanges() {
this.userData.triggerID = this.triggerID;
}
}
盡管由于您有多個輸入,但每次您的任何 Input() 接收到一個值時都會觸發此輸入,這并不好。因此,您可以為此使用 set 方法,例如:
export class TriggerformComponent implements OnInit{
@Input() set triggerID(id: any) {
this.userData.triggerID = id;
}
userData = {
triggerID: '',
};
}
只有當 triggerID Input() 接收到一個值時,userData 中的 triggerID 才會被初始化,并在每次從父級向子級傳遞一個新值時更新。
我不確定我是否理解不可編輯的值部分,如果您的意思是禁用輸入,您可以在輸入標簽中添加禁用屬性
<input type="text" name="triggerID" [(ngModel)]="userData.triggerID" disabled><br><br>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510620.html
上一篇:單選按鈕,兩個按鈕都被選中
