2017-08-09 19 views
0

我有一個反應式,有兩個選擇下拉列表。根據第一個選擇的值,第二個可能或可能不需要。Angular2/4 - 反應形式,如何動態設置和清除所需的驗證器

這是在第一個值發生變化時觸發的代碼。它基本上搜索一個數組以查看它們是否匹配類型,如果它將它們分配給第二個下拉列表,則添加所需的驗證程序。如果沒有,則控制被禁用並且驗證器被移除。

但是,該字段在else部分仍然是必需的,整個表單被標記爲無效。那麼缺少什麼?

getCategoryTypes(value: string) { 
    let types = this.categories.find(v => v.name === value); 
    if (types) { 
     this.categoryTypes = types.category_types; 
     this.category_type.setValue(""); 
     this.category_type.setValidators([Validators.required]); 
     this.category_type.updateValueAndValidity(); 
    } 
    else { 
     this.categoryTypes = []; 
     this.category_type.setValidators(null); 
     this.category_type.updateValueAndValidity(); 
    }; 
    } 

據透露:

category_type: FormControl; 

UPDATE

在文檔我發現this

「這些狀態是互斥的,所以控制不能同時有效,無效或無效且禁用。「

「禁用控制是從驗證檢查豁免和不包含在它們的祖先的控制的總價值」。

因此,禁用控件應自動刪除驗證並將控件標記爲有效。

+0

沒有足夠的信息來重現問題。代碼在這裏看起來很好。也許創造一個展示問題的闖入者? – Alex

+0

它是否正在執行此邏輯的適當分支? – DeborahK

+0

你試過這個:'this.category_type.clearValidators();' – DeborahK

回答

1

如果(類型)檢查不起作用,但我也發現沒有必要刪除並重新添加驗證,我可以禁用並重新啓用該控件。所以解決辦法是:

getCategoryTypes(value: string) { 
    let types = this.categories.find(v => v.name === value).category_types; 
    if (types.length > 0) { 
     this.categoryTypes = types; 
     this.category_type.setValue(""); 
     this.category_type.enable(); 
     this.category_type.updateValueAndValidity(); 
    } 
    else { 
     this.categoryTypes = []; 
     this.category_type.disable(); 
     this.category_type.updateValueAndValidity(); 
    }; 
    }