从组件外部提交表单



我有组件about.component.ts

onSubmit(redirectAfter) {
if (this.form.invalid) {
this.notificationService.error(this.translateService.instant('fail'));
return;
}
....

现在在about.html.ts

<user [form]="this.form"></user>

现在在带有标签用户<user>的组件中:

@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
@Input() form?: FormGroup;
validateAndClose() {
this.form.onSubmit(false);
}

所以我想在用户组件中调用关于组件中表单的提交。我试过这样,但没有工作。你有什么想法吗?提前感谢。

您可以尝试从用户组件中@Output((一个自定义事件,该事件将在关于组件中触发提交

@Output() public submitEvent = new EventEmitter();

然后在关于组件模板中:

<user-component (submitEvent)="submit()"></user-component>

一个简单的解决方案是使用事件。 您可以在子组件中创建输出事件发射器。 父级对该事件做出反应。

<user-component (formSubmit)="parentSubmitFunc()"></user-component>

.

@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
@Output() formSubmit = new EventEmitter<any>(); // <--
validateAndClose() {
[...]
formsubmit.emit(anypayload); // <--
}

文档在这里

还有另一种方法可以在不使用事件发射器的情况下访问父组件方法Output方法。这是通过使用@Host.

export class UserComponent implements OnInit {
@Input() form?: FormGroup;
parentCmp: AboutComponent;
constructor(@Host parentCmp: AboutComponent){
this.parentCmp = parentCmp;
}
validateAndClose() {
this.parentCmp.onSubmit()
}

限制:父方法不应是私有的

使用@Host进行演示

最新更新