首页 > 解决方案 > 在 Angular 8 中单击时触发 NgOninit 中的事件

问题描述

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

但是我希望作为默认值,如果页面是第一次加载的,那么您已经看到了表单。我在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)
    });
  }

标签: javascriptangulardom-events

解决方案


尝试nativeElement.click()

this.fileInput.nativeElement.click()

推荐阅读