我有一个点击事件。如果您单击该按钮,则可以填写一个小表格。
但是我想作为默认值,如果页面是第一次加载的,那么您已经看到了表单。我在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()