Angular 2组件不适用于* ngIf

时间:2017-04-05 12:22:59

标签: angular

我有一个错误消息组件,一次显示一条与* ngIf不兼容的错误消息,因此我必须使用ngClass操纵它的可见性,我不太明白为什么。

<input type="text" id="email" class="form-group__input"
    pAutofocus
    required
    email
    name="email"
    [(ngModel)]="model.email"
    #email="ngModel"
>

而不是:

<p-errors [control]="email" *ngIf="email.touched">
    <p-error name="required">Please enter your email.</p-error>
    <p-error name="email">Please make sure that your email is a valid one.</p-error>
</p-errors>    

我必须这样做:

<p-errors [control]="email" [ngClass]="{'display--none': email.untouched}">
    <p-error name="required">Please enter your email.</p-error>
    <p-error name="email">Please make sure that your email is a valid one.</p-error>
</p-errors>

没有* ngIf,结构如下所示:其中一条错误消息为true,另一条为null:

enter image description here

但是使用* ngIf,即使* ngIf为真,错误也都为空:

enter image description here

P-error.component.ts

import { Component, Input } from '@angular/core';

@Component({
    selector: 'p-error',
    template: `
        <div class="form-group__error-message"
            *ngIf="show"
        >
            <ng-content></ng-content>
        </div>
    `
})
export class PErrorComponent {
    @Input() name: string;
    show: boolean = false;
}

P-errors.component.ts

import {
    Component, Input,
    QueryList, ContentChildren, AfterContentInit, OnDestroy
} from '@angular/core';
import { FormControl } from '@angular/forms';

import { Subscription } from 'rxjs/Subscription';

import { PErrorComponent } from './p-error.component';

@Component({
    selector: 'p-errors',
    template: `<ng-content></ng-content>`
})
export class PErrorsComponent implements AfterContentInit, OnDestroy {
    @Input() control: FormControl;
    @ContentChildren(PErrorComponent) contentChildren: QueryList<PErrorComponent>;

    private statusChangesSubscription: Subscription;

    updateErrors(status: string) {
        let showError: string;
        const errors: string[] = status === 'INVALID' ? Object.keys(this.control.errors) : [];
        loop: for (const error of errors) {
            if (this.control.hasError(error)) {
                showError = error;
                break loop;
            }
        }
        this.contentChildren.forEach((pErrorComponent: PErrorComponent) => {
            pErrorComponent.show = pErrorComponent.name === showError ? true : false;
        });
    }

    ngAfterContentInit() {
        this.updateErrors(this.control.status);
        this.statusChangesSubscription = this.control.statusChanges.subscribe((status: string) => {
            this.updateErrors(status);
        });
    }

    ngOnDestroy() {
        this.statusChangesSubscription.unsubscribe();
    }
}

如果我能理解为什么会这样,那就太棒了。在我继续之前,我觉得我必须明白这一点。

0 个答案:

没有答案