Angular:表单验证导致错误

时间:2017-04-13 09:50:01

标签: forms validation angular

我是Angular的新手,我的基础是这个练习:forms。该示例告诉我们使用#name属性并将其分配给“name”。但是,该属性已用于检索提交表单的数据(如上一条规则所示)。尝试定义自己的名字时收到错误:

Cannot read property 'name' of undefined

我对此的运作方式感到有些困惑。

<form method="post">
    <div class="form-group">
        <label for="inputName">Name</label>
        <input #name type="text" class="form-control" id="inputName" placeholder="Name" required minlength="2" maxlength="20"
        name="companyName" [(ngModel)]="company.name" #companyName="ngModel">

        <div *ngIf="companyName.errors && (companyName.dirty || companyName.touched)" class="alert alert-danger">
            <div [hidden]="!companyName.errors.required">Name is required</div>
            <div [hidden]="!companyName.errors.minlength"> Name must be at least 2 characters long.</div>
            <div [hidden]="!companyName.errors.maxlength">Name cannot be more than 20 characters long.</div>
        </div>
    </div>   
    <button type="submit" class="btn btn-default" (click)="add(name.value, street.value, number.value, zipCode.value, city.value, iban.value, telephone.value)">Submit</button>
</form>

我的公司对象:

export class Company {
    name: string;
    street: string;
    number: string;
    zipCode: string;
    city: string;
    iban: string;
    telephone: string;

    constructor(name: string, street: string, number: string, zipCode: string, city: string, iban: string, telephone: string) {
        this.name = name;
        this.street = street;
        this.number = number;
        this.zipCode = zipCode;
        this.city = city;
        this.iban = iban;
        this.telephone = telephone;
    }
}

1 个答案:

答案 0 :(得分:0)

只需删除<ScrollViewer Background="White"> <ScrollViewer.Resources> <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">30</sys:Double> </ScrollViewer.Resources>--> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBlock FontSize="26" FontFamily="VAG Rounded" FontWeight="Bold" Text="April 14, 2017" /> <TextBlock FontSize="26" Margin="25" Grid.Row="1"> <Run Text="• Updates galore!" /> <LineBreak /> <Run Text="-------------------------------------------------------------------------------------------------------------------" /> </TextBlock> </Grid> </ScrollViewer> 并改为使用#name

https://angular.io/docs/ts/latest/guide/forms.html