javascript - 在 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)
});
}
解决方案
尝试nativeElement.click()
:
this.fileInput.nativeElement.click()
推荐阅读
- angular - 我有一个 JSON 数据,我想在 paper.JS 中使用 Angular 8
- reactjs - 无法在 react/redux 的 onChangeHandler 函数中过滤道具列表
- input - 如何使用输入值作为字体大小?
- wordpress - Woocommerce 在同一页面上使用购物车和结帐时隐藏 cart_totals
- ag-grid - ag-grid select all 不会通过分页选择网格中的所有行
- image-capture - 在 jetson TX2 上使用 V4L2 捕获图像
- python - div类中span标签的Web抓取
- sql - 窗口滞后 sqlzoo.net #7
- apache-spark - 我正在使用 Google Cloud dataproc 集群运行 Spark。写入 GCS 的数据集卡在未完成的 1 个任务中
- arrays - 如何根据我的文本框在二维数组中搜索一个单词,并在 MS Access 表单中使用 vba 代码