如何在Angular的FormBuilder.group字段中用if条件替代三元运算符
用if条件替代嵌套三元运算符设置Angular表单字段值
你可以通过先声明变量存储字段值,再用if分支逻辑赋值的方式替代嵌套三元,代码可读性会更高,且逻辑和原代码完全一致:
ngOnInit(): void { // 先设置默认值,对应原三元最外层的else分支 let booleanInputValue = false; if (this.ppf.type === 'boolean') { // 处理boolean类型的情况 if (this.finalValue === undefined) { this.finalValue = false; booleanInputValue = this.finalValue; } else { booleanInputValue = this.finalValue; } } this.parameterForm = this.formBuilder.group({ booleanInput: booleanInputValue }); }
如果想进一步简化内层逻辑,还可以用空值合并运算符??替代内层的if判断,效果和原代码完全一致:
ngOnInit(): void { let booleanInputValue = false; if (this.ppf.type === 'boolean') { // 若finalValue为undefined,将其设为false,否则保持原值 this.finalValue = this.finalValue ?? false; booleanInputValue = this.finalValue; } this.parameterForm = this.formBuilder.group({ booleanInput: booleanInputValue }); }
内容的提问来源于stack exchange,提问作者Tned
相关产品推荐
相关产品推荐

