Angular 4:子组件呈现两次

时间:2018-02-05 12:00:46

标签: angular

我正在学习Angular 4并调整Angular heroes tutorial,我在渲染子组件时遇到了问题。

子组件(QvSummaryComponent)应显示父子项(QvSetupComponent)加载的模型(QvSetup)的两个属性(code和versionNumber)。

app.module.ts:

@NgModule({
imports: [BrowserModule],
declarations: [
    QvSetupComponent,
    QvSummaryComponent,
    QvOtherChildComponent],
bootstrap: [
    QvSetupComponent,
    QvSummaryComponent,
    QvOtherChildComponent]
})

setup.model.ts:

export class QvSetup {
    code: string;
    versionNumber: number;
}

setup.component.ts(父组件):

export class QvSetupComponent implements OnInit {
    private qvSetup: QvSetup;

    constructor(private readonly qvSetupService: QvSetupService) { }

    ngOnInit() {
        this.loadQvSetup();
    }

    loadQvSetup(): void {
        // Hardcoded for the moment. It will come from the service later.
        this.qvSetup = new QvSetup();
        this.qvSetup.code = "MYCODE";
        this.qvSetup.versionNumber = 1;

        // Debug message (to remove)
        console.info("QvSetupComponent: loaded " + this.qvSetup.code + "-" + this.qvSetup.versionNumber);
    }
}

setup.component.html:

<h1>Setup <small>{{qvSetup.code}}{{qvSetup.versionNumber}}</small></h1>
<qvSummary
    [code]="qvSetup.code"
    [versionNumber]="qvSetup.versionNumber">
    Loading summary...
</qvSummary>
<qvOtherChildComponent>
    Loading other child component...
</qvOtherChildComponent>

qvSummary.component.ts:

export class QvSummaryComponent implements OnInit {
    @Input() code: string;
    @Input() versionNumber: number;
    private qvSummary: QvSummary;

    constructor() {
        this.qvSummary = new QvSummary();
    }

    ngOnInit() {
        if (this.code != null) {
            console.info("QvSummaryComponent: Code-VersionNumber = " + this.code + "-" + this.versionNumber);
        } else {
            console.info("QvSummaryComponent: Code-VersionNumber = null");
        }
    }
}

qvSummary.component.html:

{{qvSetup.code}}-{{qvSetup.versionNumber}}

当我执行我的脚本时,我可以在控制台中看到:

QvSetupComponent: qvSetup loaded MYCODE-1
QvSummaryComponent: code-versionNumber = MYCODE-1
QvSummaryComponent: code-versionNumber = null

它似乎渲染了两次子组件。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题来自app.model.ts。 QvSummaryComponent不应该在引导程序列表中。

新的app.module.ts:

@NgModule({
    imports: [BrowserModule],
    declarations: [
        QvSetupComponent,
        QvSummaryComponent,
        QvOtherChildComponent],
    bootstrap: [QvSetupComponent]
})