4

我有一个通过自定义双向绑定main-component将变量传递给另一个组件的方法。sub-component传递的变量通过 用于输入标签ngModel

这两个变量目前不同步。如何链接这两个变量?

主要组件.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>

子组件.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}}

鉴于上述配置,我希望you.name主组件中的变量variable和子组件中的变量同步。

如何做到这一点?

4

1 回答 1

3

你应该用 onModelChange()在孩子身上。这是一个例子:

演示

孩子:

  @Input() name;
  @Input() surname;
  @Input() age;

  @Output() nameChange = new EventEmitter();
  @Output() surnameChange = new EventEmitter();
  @Output() ageChange = new EventEmitter();


  onModelChange(event, type) { 
    this[`${type}Change`].emit(event); //this line was optimised by yurzui
  }

家长

@Component({
  selector: 'my-app',
  template: `
      <child [(name)]="name" [(surname)]="surname" [(age)]="age"></child>
      <br><br>
      Name :{{name}} 
      <br>
      Surname: {{surname}} 
      <br>
      Age: {{age}} 
      <br>
      <button (click)="reset()">Reset</button>
  `,
})
export class AppComponent implements OnInit{
  name:string;
  surname:string;
  age:number;


  reset(){
    this.name = "";
    this.surname = "";
    this.age = 18;
  } 

  ngOnInit(){
    this.reset();
  }

}
于 2017-09-19T18:24:59.747 回答