我有一个通过自定义双向绑定main-component
将变量传递给另一个组件的方法。sub-component
传递的变量通过 用于输入标签ngModel
。
这两个变量目前不同步。如何链接这两个变量?
主要组件.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-main-component',
templateUrl: './main-component.component.html',
styleUrls: ['./main-component.component.css']
})
export class MainComponentComponent implements OnInit {
private you: any = {};
constructor() { }
ngOnInit() {
this.you.name = "Name";
}
}
main.component.html
<div>
This is the main component.
you.name = {{you.name}}
<br>
<app-sub-component [(variable)]="you.name"></app-sub-component>
</div>
子组件.ts
import { Component, OnInit, OnChanges, Input, Output, EventEmitter, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-sub-component',
templateUrl: './sub-component.component.html',
styleUrls: ['./sub-component.component.css']
})
export class SubComponentComponent implements OnInit, OnChanges {
constructor() { }
@Input() variable: any;
@Output() variableChange: EventEmitter<any> = new EventEmitter<any>();
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
}
sub.component.html
<input type="text" [(ngModel)]="variable">
Variable = {{variable}}
鉴于上述配置,我希望you.name
主组件中的变量variable
和子组件中的变量同步。
如何做到这一点?