角度2子级引用变量到父级 [英] angular 2 child reference to variable into parent

查看:43
本文介绍了角度2子级引用变量到父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to change the value of a variable or use a method in a parent component from a child component without using input and output

我尝试了类似的方法,但是没有用.

I try something like this but not working.

@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'
  }
}

此处示例

朋克示例

推荐答案

输入和输出仅用于此目的.根据Angular2文档,它是为父级和子级组件之间的通信而设计的.

Input and Output are just made for this. It is, according to the Angular2 Documentation, made for communication between parent and child components.

@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个服务实例.

Alternatively you could inject a service into both parent and child component, which has some values that both parent and child can access and modify. But make sure to add that service to either only the parent component or only the AppModule, otherwise you would get 2 instances of your service.

这篇关于角度2子级引用变量到父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆