如何在父组件的* ngIf中调用子组件变量?

时间:2016-12-07 13:21:52

标签: angular typescript components

我是网络开发的新手。我正在学习Angular2和Typescript。

我想开发一个Tab组件,它有2个子组件,即Header和Content。标题是标题标题,内容是这些标题内的内容。我想将appcomponent.html中的tab组件称为:

<VarTab>

 <VarTabHeader name="profile">profile</VarTabHeader>
 <VarTabHeader name="messages">messages</VarTabHeader>
 <VarTabHeader name="home">home</VarTabHeader>

 <VarTabContent name="profile">profile content</VarTabContent>
 <VarTabContent name="messages">messages content</VarTabContent>
 <VarTabContent name="home">home content</VarTabContent>

</VarTab>

并希望在正确的标题内显示每个内容。

这是我的标题组件:

@Component({
selector: 'VarTabHeader',
template: `
`})

export class VarTabHeader {
@Input() name:string="";

@Output() select = new EventEmitter<TabEvent>();

ngClick(){
    let event:TabEvent = new TabEvent();
    this.select.emit(event);
}
}

这是我的内容组件:

@Component({
selector: 'VarTabContent',
template: `
`})

export class VarTabContent {
@Input() name:string;
}

最后,Tab组件是:

@Component({
selector: 'VarTab',
template: `
    activeTabNo: {{activeTabNo}}
    <div class="vartab">

        <ul class="nav nav-tabs">
            <li role="presentation" (click)="tabClicked(i)"  *ngFor="let header of headerArray; let i = index"  
                [class.active]="header.order === activeTabNo" > <a href="#">{{header.name}}</a> </li>
        </ul>

        <div *ngFor = "let content of contentArray; let i = index" > 
            <span *ngIf="content.name==='headerArray[activeTabNo].name'">{{content.name}}</span>
        </div>

    </div>
`
})

export class VarTab {
public activeTabNo:number=0;
public activeTabName:string="";
private headerArray:VarTabHeaderModel[];
private contentArray:VarTabContentModel[];


@ContentChildren(VarTabHeader) headers: QueryList<VarTabHeader>;
@ContentChildren(VarTabContent) contents: QueryList<VarTabContent>;
@Output() tabChanged = new EventEmitter<number>();

tabClicked(activeTabNo:number){
    this.activeTabNo = activeTabNo;
    this.activeTabName = this.headerArray[activeTabNo].name;
    this.tabChanged.emit(this.activeTabNo);
}

copyHeaderView(declaredHeaders:QueryList<VarTabHeader>) {
    // pushes all headers inside an array
}

copyContentView(declaredContents:QueryList<VarTabContent>) {
    // pushes all contents inside an array
}

headerOrder(key:string){
    // gives the order of header
}

initTab(){
    this.headerArray = this.copyHeaderView(this.headers);
    this.contentArray = this.copyContentView(this.contents);
}

ngAfterContentInit(){
    this.initTab();
}
}  

在这里,我设法将所有标题放在数组中并以正确的顺序显示它们,但是

<div *ngFor = "let content of contentArray; let i = index" > 
    <span *ngIf="content.name==='headerArray[activeTabNo].name'">{{content.name}}</span>
</div>

此代码不起作用,因为i和activeTabNo不匹配,并且不在页面上写入content.name。

任何帮助将不胜感激。谢谢!

0 个答案:

没有答案