从附加到<form>的指令中访问FormGroup实例

时间:2018-12-14 16:26:43

标签: angular angular-directive

HTML

 class TodoApp extends React.Component {

       constructor(props){
         super(props);
         this.state = {
            scriptString: ''
         };
       }
       handleKeyDown(event) {
          if (event.keyCode === 9) { // tab was pressed
              event.preventDefault();
              var val = this.state.scriptString,
                  start = event.target.selectionStart,
                  end = event.target.selectionEnd;

              this.setState({"scriptString": val.substring(0, start) + '\t' + val.substring(end)}, () => this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1);
          }
      }
      onScriptChange(event) {
         this.setState({scriptString: event.target.value});
      }
      render() {
          return (
              <textarea rows="30" cols="100" autofocus="true"
                        ref={this.textareaInput}
                        rows={1}
                        onFocus={ this.onFocus } 
                        onKeyDown={this.handleKeyDown.bind(this)}
                        onChange={this.onScriptChange.bind(this)} 
                        value={this.state.scriptString}/>



          );
      }
    }

    ReactDOM.render(
      <TodoApp />,
      document.getElementById('container')
    );

表单指令。

<form [formGroup]="form">
  <input type="text" formControlName="name" class="form-control" />
  <div *errorFeedback name="name" class="error-feedback"></div>
</form>

* errorFeedback指令

@Directive({
  selector: 'form'
})
export class FormGroupErrorDirective implements OnInit, AfterContentChecked {

  @ContentChildren(ErrorFeedbackDirective) errorFeedbackDirectives: QueryList<ErrorFeedbackDirective>;

  ngAfterContentChecked(): void {
    this.errorFeedbackDirectives.forEach(dir => {
      // ???? How can I get this.formGroup ???
      dir.formControl = this.formGroup.get(dir.formControlName);
    });
  }

}

如何从// tslint:disable:directive-selector @Directive({ selector: '[errorFeedback]', }) export class ErrorFeedbackDirective implements OnInit { // tslint:disable:no-input-rename @Input('errorFeedback') name: string; formControl!: FormControl; constructor(private el: ElementRef, private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { } ngOnInit() { } } 内部访问FormGroup指令实例?

我在这里要做的是将FormControl实例传递给FormGroupErrorDirective指令。然后,我将使用它来观察状态更改和错误。

还是有更好的方法来访问*errorFeedback中的FormControl实例?

3 个答案:

答案 0 :(得分:1)

可以通过在指令构造函数方法中声明如下属性来访问FormGroup

import { ControlContainer } from '@angular/forms';

constructor(private readonly form: ControlContainer) { }

答案 1 :(得分:1)

您可以在指令构造函数中使用FormGroupDirective类:

constructor(private fg: FormGroupDirective) {
    this.fg = fg;
    console.log(this.fg.form)// print your form group 
}

在您的模板中:

<div [formGroup]="editFormGroup" yourDirective>
</div>

答案 2 :(得分:0)

我写了一条指令,允许您从指令内访问FormGroup。目前,它有点破烂,但效果很好。我的指令允许您基于可观察的值设置表单值

https://stackblitz.com/edit/angular-reactive-form-directive

您可以根据需要对其进行调整

constructor(private vr: ViewContainerRef) {}

ngAfterContentInit() {
  let componentProperties = (this.vr as any)._hostView[8];
  let form: FormGroup;
  
  // Find the form in the component
  for (let property of Object.keys(componentProperties)) {
    if (componentProperties[property].__proto__.constructor.name === "FormGroup") {
      form = componentProperties[property];
    }
  }
  
  //DO SOMETHING WITH form
}