javascript - 在 Angular 8 中单击时在 NgOninit 中触发事件

标签 javascript angular dom-events

我有一个点击事件。如果你点击它,你可以填写一个小表格。

但我希望默认值是,如果页面是第一次加载,那么您已经看到了表单。我在 NgOninit 中尝试了它。

所以我将其作为 html:

<button mat-button mat-icon-button #nodeInput (click)="addNode($event)"><mat-icon>add</mat-icon></button>

这是方法:

 addNode(model?: SchemaTemplateNodeDTO) {
    const newControl = this.fb.control(model ? model : null, [Validators.required]);

    const node = {
      id: this.idGen++,
      children: []
    };

    // Add node to tree and form
    this.idToFormControl.set(node.id, newControl);

    const nodes = this.form.controls['nodes'] as FormArray;
    nodes.push(newControl);

    this.dataSource.data.push(node);

    // Refresh tree
    this.dataSource.data = this.dataSource.data;
  }

我现在在 NgOniti 中拥有它,就像这个:


@ViewChild('nodeInput' ) fileInput: ElementRef;
ngOnInit() {

    this.fileInput.nativeElement.dispatchEvent(event);

    this.addNode();

  }

如果我这样尝试:


  ngOnInit() {

    this.fileInput.nativeElement.click();
  }

然后我会得到这个错误:

<button mat-raised-button color="accent" (click)="saveAndPublish()" [disabled]="form.invalid">Save & Publish</button>
<button mat-raised-button color="primary" (click)="save()" [disabled]="form.invalid">Save</button>
<form [formGroup]="form">
  <app-node-tree-input formControlName="nodes"></app-node-tree-input>
</form>

所以在另一个组件中。

这是另一个组件的一部分:

export class EditSchemaComponent implements OnInit {
  private schema: SchemaTemplateDTO;

  private fb: FormBuilder;
  form: FormGroup;

  public readonly displayedColumns = ["title", "published", "pages", "createdOnUtc", "createdBy", "edit"];

  constructor(
    private i18n: I18n,
    private schemaTemplateService: SchemaTemplateService,
    private blockerService: ScreenBlockerService,
    route: ActivatedRoute
  ) {
    this.schema = route.snapshot.data["schema"];
  }

  ngOnInit() {
    this.fb = new FormBuilder();
    this.form = this.fb.group({
      nodes: this.fb.control(this.schema.nodes)
    });
  }

最佳答案

尝试使用 nativeElement.click():

this.fileInput.nativeElement.click()

关于javascript - 在 Angular 8 中单击时在 NgOninit 中触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57973282/

相关文章:

Angular 2 提前编译器未找到 ngfactory?

javascript - 火狐扩展。 DOMContentLoaded 在某些页面上多次触发

javascript - jsx图点更新事件

javascript - 在 Backbone View 中触发 el 事件

javascript - CSS-JAVASCRIPT Object.style.display = 值不工作(旋转设备)

javascript - 函数的 $q promise 在解析时不会将其值传播到 Angular View 中

javascript - Angular 2 和 TypeScript。如何编译HTML模板?

javascript - 我应该使用哪种方法从文本中提取指定的数据?

javascript - 我怎样才能在 HTML 中运行它?

javascript - 等待 promise 内的函数完成