I have main-component
one that passes a variable to another component sub-component
through a custom two-way binding. The skipped variable is used for the input tag through ngModel
.
These two variables are not currently synchronized. How can I bind these two variables?
main.component.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>
sub.component.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}}
Given the configuration above, I want the variable you.name
in the main component and the variable variable
in the subcomponent to be synchronized.
How can this be achieved?
source
share