Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 如何在Angular typescript中而不是表单中执行字段验证?_Html_Angular - Fatal编程技术网

Html 如何在Angular typescript中而不是表单中执行字段验证?

Html 如何在Angular typescript中而不是表单中执行字段验证?,html,angular,Html,Angular,由于特定的要求,我需要验证typescript代码中是否存在我的delivery.address字段,因此我调用了一个函数addressIsValid(),如下面的代码所示 <div class="col col-md-6 col-lg-12"> <input class="form-control" type="text" name="address" id="address" [(ngModel)]="delivery.address" #address="ngM

由于特定的要求,我需要验证typescript代码中是否存在我的delivery.address字段,因此我调用了一个函数addressIsValid(),如下面的代码所示

<div class="col col-md-6 col-lg-12">
<input class="form-control" type="text" name="address" id="address" 
    [(ngModel)]="delivery.address" #address="ngModel">
    <ng-container *ngIf="delivery.method=='Delivery'">
        <div *ngIf="!addressIsValid()" class="primary-color">
            <!-- <div *ngIf="address.invalid && (address.dirty 
                || address.touched)" class="primary-color"> -->
            Address is required
            <!-- </div> -->
        </div>
    </ng-container>
</div>

问题是在字段中输入有效值后,错误消息“Address is required.”不会消失。如何修复此问题?

您可能想检查此问题:

public addressIsValid() {
    return !!this.delivery.address;
  }

如果不是这样,则需要在方法调用后调试this.delivery实际包含的内容

console.log(this.delivery)

告诉我们它包含什么。

我认为问题出在您的
addressIsValid
函数中

以这两个对象为例:

const o={name:'john'};
常量o2={name:未定义};
!o、 名称
-->
错误

!o2.名称
-->
true

上述两项均不满足条件
==undefined
==null

因此,您总是会得到一个错误的值

您可以这样修改您的函数:

公共地址有效(){
返回this.delivery.address!==未定义
&&this.delivery.address!==null;
}

我建议你读一下。您可以在TypeScript中轻松定义验证规则,并在视图中驱动错误消息的显示

this.heroForm=new FormGroup({
“名称”:新FormControl(this.hero.name[
需要验证器,
验证器。最小长度(4),
验证程序(/bob/i)//
console.log(this.delivery)