Bidirectional data binding on a component input property

前端 未结 4 1848
名媛妹妹
名媛妹妹 2021-02-19 07:24

I am trying to make something work on angular2 and I am unable to find something about this behavior.

I have an application that implements a custom component like this

4条回答
  •  一整个雨季
    2021-02-19 07:58

    I'll combine @pixelbits and @Günter Zöchbauer answers and comments to make a clear answer on my question if someone in the future is searching for this.

    To make bidirectional data binding works on custom variables you need to creates your component based on the following.

    MyComp.ts file :

    import {Component,Input,Output,EventEmitter} from 'angular2/core'
    @Component({
      selector:'my-comp',
      templateUrl:``
    })
    
    export class MyComp{
      @Input() inputText : string;
      @Output() inputTextChange = new  EventEmitter();
    }
    

    MyApp.ts file:

    import {Component} from 'angular2/core'
    import {MyComp} from './MyComp'
    
    @Component({
      selector:'my-app',
      templateUrl:`

    Bidirectionnal Binding test

    My Test String : {{testString}}

    `, directives:[MyComp] }) export class MyApp{ testString : string; constructor(){ this.testString = "This is a test string"; } }

    There the bidirectional data binding to the inputText variable works correctly. You can comment the answer for a more beautiful or simpler way to implement this code.

提交回复
热议问题