2016-08-01 163 views
3

我想知道使用依赖注入组件和@ViewChild有什么区别。这两种方式我都可以使用父属性方法。所以,当我应该和其他人?Angular2依赖注入vs @ViewChild

依赖注入

import { Component, OnInit } from '@angular/core'; 
import { CompB } from './compb/compb.component'; 

@Component({ 
    moduleId: module.id, 
    selector: 'app-test', 
    templateUrl: 'compA.html' 
}) 
export class CompAComponent implements OnInit { 

    constructor(private _compB: CompB) { 
    } 
    ngOnInit() { 
     this._compB.getName(); 
    } 

} 

@Component({ 
    moduleId: module.id, 
    selector: 'app-test', 
    templateUrl: 'compB.html' 
}) 
export class CompBComponent { 
    getName() { 
     return 'Hello World'; 
    } 
} 

@ViewChild

import { Component, OnInit } from '@angular/core'; 
import { CompB } from './compb/compb.component'; 

@Component({ 
    moduleId: module.id, 
    selector: 'app-test', 
    templateUrl: 'compA.html' 
}) 
export class CompAComponent implements OnInit { 
    @ViewChild(CompB) compB: CompB 
    ngOnInit() { 
     this._compB.getName(); 
    } 

} 

@Component({ 
    moduleId: module.id, 
    selector: 'app-test', 
    templateUrl: 'compB.html' 
}) 
export class CompBComponent { 
    getName() { 
     return 'Hello World'; 
    } 
} 

正如你可以看到,这两种方法我可以访问的getName()在compBComponent。

回答

2

我认为名字应该是明显不够......

@ViewChild给你参考到您的视图中创建一个实际的视图的孩子。孩子的一生完全取决于当前组件的生命周期。

Injectable component返回由Angular的DI模块创建的指定类(看起来是一个组件)的对象。该对象的生命周期将由Angular的DI规则管理(您将其放入此providers array)。

在你的例子中,没有什么区别,因为Component可以是一个可注入的对象,而你的getName函数更可能属于服务而不是组件。 Component被设计成一个可见模块,向用户显示信息或从中获取信息。再举一个例子,在compBComponent中有一个输入,允许用户输入新名称,如果没有用户输入,getName将会脱离上下文。在这种情况下,DI compBComponent将变得不相关。

与之一起玩的调子(更新到最后):http://plnkr.co/edit/dn9CiGUrswW2FQgLPWwW

+0

谢谢您的澄清!现在很清楚应该如何以及何时使用它!干杯。 –

+0

重击者需要更新。 – Shivam

+0

只是。请享用 :) –