Angular2 - two way databinding on a component variable / component class property?

后端 未结 2 1369
我寻月下人不归
我寻月下人不归 2020-12-24 02:21

In Angular2 (Beta 6) I have a component for a main menu.


I want to bind a boolean for wide or narrow. So

2条回答
  •  时光说笑
    2020-12-24 03:13

    I've created a short plunkr.

    ngModel Like Two-Way-Databinding for components

    You have at least two possibilities to to create a two way databinding for components

    V1: With ngModel Like Syntax, there you have to create a @Output property with the same name line the @Input property + "Change" at the end of the @Output property name

    @Input() name : string;
    @Output() nameChange = new EventEmitter(); 
    

    with V1 you can now bind to the Child Component with the ngModel Syntax

    [(name)]="firstname"
    

    V2. Just create one @Input and @Output property with the naming you prefer

    @Input() age : string;
    @Output() ageChanged = new EventEmitter();
    

    with V2 you have to create two attributes to get the two way databinding

    [age]="alter" (ageChanged)="alter = $event"
    

    Parent Component

    import { Component } from '@angular/core';
    
    @Component({
       selector: 'my-app',
       template: `

    V1 Parentvalue Name: "{{firstname}}"


    V2 Parentvalue Age: "{{alter}}"


    ` }) export class AppComponent { firstname = 'Angular'; alter = "18"; }

    Child Component

    import { Component, Input, Output, EventEmitter } from '@angular/core';
    
    @Component({
       selector: 'my-child',
       template: `

    V1 Childvalue Name: "{{name}}"


    V2 Childvalue Age: "{{age}}"

    ` }) export class ChildComponent { @Input() name : string; @Output() nameChange = new EventEmitter(); @Input() age : string; @Output() ageChanged = new EventEmitter(); public onNameChanged() { this.nameChange.emit(this.name); } public onAgeChanged() { this.ageChanged.emit(this.age); } }

提交回复
热议问题