Angular:子组件中自定义输入的 2 种数据绑定方式
Angular: 2 way data binding for a custom input in a child component
如何在 Angular8 中为子组件中的自定义输入进行双向数据绑定?
我使用了盒子里的香蕉 [(...)]
语法,但它不会使子组件的更改在父组件中可见。
在结果中,它应该使用盒子里的香蕉语法。
parent.component.ts
...
public childVisibility: boolean = true;
...
parent.component.html
childVisibility : {{childVisibility}}
<app-child-component [(visible)]="childVisibility">
</app-child-component>
child.component.ts
@Component({
selector: 'app-child-component',
templateUrl: './app-child.component.html',
styleUrls: ['./global-search-results.component.scss']
})
export class ChildComponent {
@Input() visible: boolean;
constructor() {}
public changeVisible() {
this.visible = false;
}
}
child.component.html
<button (click)="changeVisible()">
Change Visible
</button>
这样试试:
child.component.ts:
@Output() visibleChange = new EventEmitter();
public makeVisible() {
this.visible = false;
this.visibleChange.emit(this.visible)
}
parent.component.html
<app-child-component [(visible)]="childVisibility" >
</app-child-component>
child.component.ts
@Input() visible: boolean;
@Output() visibleChange = new EventEmitter<boolean>();
public changeVisible() {
this.visible = false;
this.visibleChange.emit(this.visible);
}
parent.component.html
<app-child-component [(visible)]="childVisibility">
</app-child-component>
这里的原因是事件名称 visibleChange
中的后缀 'Change'。如果 属性 绑定名称是 'x',则事件绑定名称应该正好是 'xChange'。只有这样 angular 才能识别盒子里的香蕉 [()] 语法。
如何在 Angular8 中为子组件中的自定义输入进行双向数据绑定?
我使用了盒子里的香蕉 [(...)]
语法,但它不会使子组件的更改在父组件中可见。
在结果中,它应该使用盒子里的香蕉语法。
parent.component.ts
...
public childVisibility: boolean = true;
...
parent.component.html
childVisibility : {{childVisibility}}
<app-child-component [(visible)]="childVisibility">
</app-child-component>
child.component.ts
@Component({
selector: 'app-child-component',
templateUrl: './app-child.component.html',
styleUrls: ['./global-search-results.component.scss']
})
export class ChildComponent {
@Input() visible: boolean;
constructor() {}
public changeVisible() {
this.visible = false;
}
}
child.component.html
<button (click)="changeVisible()">
Change Visible
</button>
这样试试:
child.component.ts:
@Output() visibleChange = new EventEmitter();
public makeVisible() {
this.visible = false;
this.visibleChange.emit(this.visible)
}
parent.component.html
<app-child-component [(visible)]="childVisibility" >
</app-child-component>
child.component.ts
@Input() visible: boolean;
@Output() visibleChange = new EventEmitter<boolean>();
public changeVisible() {
this.visible = false;
this.visibleChange.emit(this.visible);
}
parent.component.html
<app-child-component [(visible)]="childVisibility">
</app-child-component>
这里的原因是事件名称 visibleChange
中的后缀 'Change'。如果 属性 绑定名称是 'x',则事件绑定名称应该正好是 'xChange'。只有这样 angular 才能识别盒子里的香蕉 [()] 语法。