加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2 v.2.3 – 让指令访问通过formControlName语法创建的For

发布时间:2020-12-17 07:58:50 所属栏目:安全 来源:网络整理
导读:所以我正在尝试制作一个可以操作FormControl的指令. 似乎如果我使用长语法来在模板中声明表单控件,我可以将控件传递给指令,以便将其作为直接@Input()绑定;即:使用以下模板: form [formGroup]="myForm" input type="text" id="myText" [formControl]="myFor
所以我正在尝试制作一个可以操作FormControl的指令.

似乎如果我使用长语法来在模板中声明表单控件,我可以将控件传递给指令,以便将其作为直接@Input()绑定;即:使用以下模板:

<form [formGroup]="myForm">
    <input type="text" id="myText" [formControl]="myForm.controls['myText']" my-directive>
</form>

以下组件逻辑:

@Component({
    // Properties go here.
})
class MyComponent {
    myForm: FormGroup;

    constructor(fb: FormBuilder) {
        // Constructor logic...
    }

    ngOnInit() {
        this.myForm = this.fb.group({
            "myText": [""]
        });
    }
}

该指令看起来像:

@Directive({
    selector: "[my-directive]"
})
class MyDirective {
    Input() formControl: FormControl;
}

但是,如果我在模板中使用formControlName语法:

<form [formGroup]="myForm">
    <input type="text" id="myText" formControlName="myText" my-directive>
</form>

我如何在指令中引用(隐式?)make FormControl?

如果你使用NgControl,ElementRef,HostListener和构造函数注入,我们可以有一个适用于formControlName或[formControl] guise甚至模板驱动形式的反应形式的表单控件的指令:
import { Directive,HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[my-directive]'
})
export class MyDirective {
  constructor(private el: ElementRef,private control : NgControl) { }

  @HostListener('input',['$event']) onEvent($event){
    let valueToTransform = this.el.nativeElement.value;
    // do something with the valueToTransform
    this.control.control.setValue(valueToTransform);
  }
}

这是一个applicable demo

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读