typescript - Why @Input() in angular 4 behaving like two way data binding not one-way? -
according knowledge input 1 way communication. changes made @input() variable inside child not reflected in parent component.
i have empty array in app component. app component have 2 child components. 1 form component(to add new entries) , second list component(to show entries). empty array passed form comp of input. change in input() array inside form component reflects in root component. , list component gets updated. here code:
app.component.ts
@component({ selector: 'app-root', template: `<div> <app-form [formelements]="serverelements"> </app-form> <app-list *ngfor = "let server of serverelements" [listserver]="server"> <app-list> </div>` }) export class appcomponent { serverelements = []; }
app-form.component.html
<div class="row"> <div class="col-xs-12"> <p>add new servers or blueprints!</p> <label>server name</label> <input type="text" class="form-control" [(ngmodel)]="newservername"> <label>server content</label> <input type="text" class="form-control" [(ngmodel)]="newservercontent"> <br> <button class="btn btn-primary" (click)="onadd()">add server</button> </div> </div>
app-form.component.ts
export class formcomponent { @input() elements=[]; newservername = ''; newservercontent = ''; constructor() { } onadd() { this.elements.push({ name: this.newservername, content: this.newservercontent }); } } app-list.component.ts @component({ selector: 'app-server-element', template: ` <div class="panel-heading">{{ server.name }}</div> <div class="panel-body"> <p>{{server.content}}</p> </div>`, }) export class listcomponent implements { @input() server; constructor() { } }
Comments
Post a Comment