Issue
Both Block1 and Block2 are same component "hello.component.ts
"(reused component)
Whatever data updating from Block1 input box should reflect on Block2 input box.
But the data updating from Block2 to Block1 should not update.
The data should update one direction, there is no multi-directional.
Currently data updating on multi-direction, difficult to get solution on this.
Please give short solution.
Solution
You see it being "multi-directional", because you're passing the same object reference to both components.
Replace that with a simple string and use inputs/outputs, like this:
// hello.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'hello',
template: `
<input type="text" [ngModel]="name" (ngModelChange)="updateName($event)" />
<h1>Hello {{name}}!</h1>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: any;
@Output() nameChanged: EventEmitter<string> = new EventEmitter();
updateName(name: string): void {
this.name = name;
this.nameChanged.emit(name);
}
}
// app.component.html
<p> Block1</p>
<hello [name]="name" (nameChanged)="name = $event"></hello>
<p> Block2</p>
<hello [name]="name"></hello>
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
}
Answered By - Thor Jacobsen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.