[英]Angular5 - Change parent's property from child component's input's [(ngModel)] binding
[英]Angular 2 ngModel in child component updates parent component property
我制作了一個簡單的 UI,它包含兩個組件(父和子)。
UI 的作用是當我在 Child 組件的輸入框中輸入一些東西時。 該值將使用 ngModel 更改。
子組件以這種方式工作正常。
// Child Component
@Component({
selector: 'child',
template: `
<p>{{sharedVar}}</p>
<input [(ngModel)]="sharedVar">
`
})
export class ChildComponent {
sharedVar: string;
}
現在我有一個父組件,我打算使用與子組件相同的值。
我將子組件添加到父模板中,並使用依賴注入來調用子組件的sharedVar
。
// Parent Component
@Component({
selector: 'parent',
template: `
<h1>{{sharedVar}}</h1>
<child></child>
`,
directives: [ChildComponent],
providers: [ChildCompnent]
})
export class ParentComponent {
sharedVar: string;
constructor(child: ChildComponent) {
this.sharedVar = child.sharedVar;
}
}
問題是當我在輸入框中輸入時, <p>
的值會自動更改,而父組件的<h1>
的值不會更改。
我們可以使用父模板中的[(x)]
語法來實現與子模板的雙向數據綁定。 如果我們創建一個名為xChange
的 Output 屬性,Angular 將自動更新父屬性。 然而,每當孩子改變值時,我們確實需要emit()
一個事件:
import {Component, EventEmitter, Input, Output} from 'angular2/core'
@Component({
selector: 'child',
template: `
<p>Child sharedVar: {{sharedVar}}</p>
<input [ngModel]="sharedVar" (ngModelChange)="change($event)">
`
})
export class ChildComponent {
@Input() sharedVar: string;
@Output() sharedVarChange = new EventEmitter();
change(newValue) {
console.log('newvalue', newValue)
this.sharedVar = newValue;
this.sharedVarChange.emit(newValue);
}
}
@Component({
selector: 'parent',
template: `
<div>Parent sharedVarParent: {{sharedVarParent}}</div>
<child [(sharedVar)]="sharedVarParent"></child>
`,
directives: [ChildComponent]
})
export class ParentComponent {
sharedVarParent ='hello';
constructor() { console.clear(); }
}
我在 ParentComponent 中使用了sharedVarParent
只是為了證明名稱在父級和子級中不必相同。
您可以設置從子級到父級的事件發射器通信( outputs
)。 例如像這樣:
@Component({
selector: 'child',
template: `
<p>Child: {{sharedVar}}</p>
<input [(ngModel)]="sharedVar" (ngModelChange)="change()">
`
})
export class ChildComponent {
@Output() onChange = new EventEmitter();
sharedVar: string;
change() {
this.onChange.emit({value: this.sharedVar});
}
}
和父組件:
@Component({
selector: 'parent',
template: `
<h1>{{sharedVar}}</h1>
<child (onChange)="sharedVar = $event.value"></child>
`,
directives: [ChildComponent]
})
export class ParentComponent {
sharedVar: string;
constructor() {
}
}
如果你想在同一個組件中有多個雙向數據綁定,你可以這樣做
export class ComponentName {
@Input() public first: string = '';
@Input() public second: string = '';
@Output() public firstChange = new EventEmitter();
@Output() public secondChange = new EventEmitter();
public functionName1(first: string): void {
this.first = first;
this.firstChange.emit(first);
}
public functionName2(second: string): void {
this.second = second;
this.secondChange.emit(second);
}
}
當輸入和輸出被命名為 'x' 和 'xChange' 時,它會在屬於一起的父級中自動檢測它們。
我認為這實際上比接受的答案中的做法更好,因為在這里它立即清楚地說明了名稱之間的關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.