2016-11-28 52 views
0

如何改变一个变量的值或在从一个子组件父组件使用的方法,而不使用输入和输出角2子参照可变进父

我尝试这样的事情,但不工作。

@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

+1

的可能的复制[Angular2:父母与孩子的组件通信](http://stackoverflow.com/questions/36316896/angular2-parent-and-child-components-communication) – Fiddles

回答

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

+0

“将该服务添加到只有父组件或只有AppModule,否则你会得到2个服务实例“ - 你能详细说明一下吗?我不清楚你的意思 – Fiddles

+0

好吧想象一下你有两个组件。如果您将abcService添加为每个组件的提供者(在您的@Component中,您可以定义一个提供者数组),那么您将拥有该服务的两个实例,因此您将不得不在数据组件之间共享数据状态。因此,请确保你在你的AppModule中声明了服务,或者只在你的父组件中声明它,然后你的子组件将采用同一个实例 – lastWhisper

+0

这很有趣,我不知道声明组件提供者创建了一个新的注入器, 。谢谢 – Fiddles