【问题标题】:angular 2 child reference to variable into parent角度 2 子变量对父变量的引用
【发布时间】:2017-04-11 15:32:34
【问题描述】:

如何在不使用输入和输出的情况下,从子组件改变变量的值或使用父组件中的方法

我尝试了类似的方法,但不起作用。

@Component({
  selector: 'child',
  template: `
    <div>
      <h2>{{name}}</h2>
      <button (click) = "rename()" > Rename Parent </button>
    </div>
  `,
})
export class Child {
  name:string;
  constructor() {
    this.name = 'child'
  }

  rename() {
    App.name = 'Rename';
  }

}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <child> </child>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

这里的例子

plunker example

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

输入和输出就是为此而生的。根据 Angular2 文档,它是为父组件和子组件之间的通信而设计的。

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <child [name]="this.name" (nameChanged)="this.name = $event"> </child>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

@Component({
  selector: 'child',
  template: `
    <div>
      <h2>{{name}}</h2>
      <button (click) = "rename()" > Rename Parent </button>
    </div>
  `,
})
export class Child {

@Input() name:string;
@Output() nameChanged: EventEmitter<string> = new EventEmitter<string>();

  constructor() {
  }

  rename() {
    this.nameChanged.emit('Renamed');
  }

}

或者,您可以将服务注入父组件和子组件,其中包含父子组件都可以访问和修改的一些值。但请确保将该服务仅添加到父组件或仅 AppModule,否则您将获得 2 个服务实例。

【讨论】:

  • "将该服务仅添加到父组件或仅 AppModule,否则您将获得 2 个服务实例" - 您能详细说明一下吗?我不清楚你的意思是什么
  • 好吧假设你有两个组件。如果您将您的 abcService 作为提供者(在您的 @Component 中,您可以定义一个提供者数组)添加到每个组件,您将拥有此服务的两个实例,因此您将不得不数据状态并且组件之间没有共享。因此,请确保您在 AppModule 中声明服务或仅在父组件中声明它,然后您的子组件将采用相同的实例
  • 这很有趣,我不知道声明组件提供者会创建一个作用于该组件树的新注入器。谢谢
【解决方案2】:

即 Angular 2 中的 @Output 和 @Input。 文档:https://angular.io/docs/ts/latest/cookbook/component-communication.html

【讨论】:

    猜你喜欢
    • 2015-08-21
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2018-04-13
    • 1970-01-01
    相关资源
    最近更新 更多