Angular 2 - 获取组件实例

3

我有两个类似这样的组件:

@Component({
    selector: 'comp1',
    template: `<h1>{{ custom_text }}</h2>`
})
export class Comp1 {
    custom_text:string;
    constructor(text:string) {
        this.custom_text = text;
    }
}

/*********************************************/

@Component({
    selector: 'comp2',
    directives: [Comp1],
    template: `
    <b>Comp 2</b>
    <comp1></comp1>
    `
})
export class Comp2 {
    constructor() {
        // ...
        // How to send my own text to comp1 from comp2
        // ...
    }
}

我可以从comp1发送自己的文本到comp2吗?

我可以从comp2获取comp1实例吗?

谢谢。


请查看此链接:http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders - TGH
2个回答

5

comp2是comp1的父组件,因此

  • 如果需要从子组件向父组件发送数据 (从comp1到comp2),需要在子组件中添加OutputProperty
    @Output() someEvent = newEventEmitter();
    然后在其上触发事件:this.someEvent.emit('some text');
    父组件需要绑定输出属性/事件:<comp2 (someEvent)="someHandler()"></comp2>
  • 如果需要获取子组件实例的引用(comp2获取comp1的引用),则可以在comp2中使用@ViewChild 或者 @Query@ViewChild(Comp1) viewChild:comp1; 然后可以在ngAfterViewInit()或组件生命周期晚些时候访问this.comp1

我开始认为这也是一个输出案例,但如果你看他的代码,他试图做一个输入案例并表达不清。我喜欢你关于发射器的答案,但通常我看到输出会使组件难以更改,因为我们需要维护回调合同,我通常更改后端以保存和传播更改,但对于最小状态数据,回调是可以的。 - C B

1

是的,非常容易实现,

请查看教程:MULTIPLE COMPONENTS Angular2教程的第三部分,了解如何发送输入。

@Component({
    selector: 'comp1',
    template: `<h1>{{customText}}</h2>`,
    inputs: ['customText']
})
export class Comp1 {
    public customText:string;
    constructor(text:string) {
        this.customText= text;
    }

 // ngOnChange to make sure the component is in sync with inputs changes in parent
 ngOnChanges() {
       this.customText= text;
    }
}

/*********************************************/

@Component({
    selector: 'comp2',
    directives: [Comp1],
    template: `
    <b>Comp 2</b>
    <comp1 customText = "My Custom Test"></comp1>
    `
})
export class Comp2 {
    constructor() {
    }
}

试一下并让我知道进展如何。


1
这会不会抛出错误?:constructor(text:string) { - Mark Rajcok
是的。但那只是一个例子。 - Jon...
1
@Jon...谢谢,是的,你原来的例子有问题。我在想/问为什么Chibi没有展示一个可行的解决方案。(这样未来的读者就不会尝试复制粘贴解决方案,只发现它不起作用。) - Mark Rajcok

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接