html - 如何在子按钮中调用父函数
问题描述
假设我有一个名为的组件ButtonComponent
,它将在应用程序的各个地方使用,所以我尽可能通用,如下所示:
button.component.ts
import { Component, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ButtonComponent{
@Input() group: FormGroup;
@Input() type: string;
@Input() description: string;
@Input() class: string;
@Input() callFunction: Function;
}
button.component.html
<div [formGroup]="group">
<button type="{{ type }}" class="{{ class }}" (click)="callFunction()">{{ description }}</button>
</div>
现在我的按钮是完全可定制的(理论上)。我现在要将它导入到一个登录组件中,该组件有一个名为login()
. 我希望我的按钮实例在单击它时运行此特定功能:
登录组件.ts
//imports
/**
* This component is rendered at the start of application, it provides the UI
* & functionality for the login page.
*/
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
/**
* This class is used to build a login form along with initialization of validators
* as well as authenticate the user, and reroute upon success
*/
export class LoginComponent implements OnInit, AfterContentInit{
@ViewChild('login', { read: ViewContainerRef }) login_button;
/**
* This property initializes the formGroup element.
*/
userForm: FormGroup;
/**
* The constructor initializes Router, FormBuilder, OauthService, LoggerService, ToastrService
* & TranslatePipe in the component.
*/
constructor(//initializations
) { }
/**
* This is the hook called on the initialization of the component, it initializes
* the form.
*/
ngOnInit() {
this.buildForm();
}
/**
* This method initialized the the formGroup element. Its properties and the validators.
*
* @method buildForm
* @return
*/
buildForm() {
// validations
});
}
/**
* This method returns the values of the form controls.
*
* @return
*/
get form() { return this.userForm.controls; }
/**
* This method is triggered on success, it reroutes the user to main page.
*
* @return
*/
onSuccess() {
let result = this.translate.transform("pages[login_page][responses][success]");
this.logger.info(result);
this.toastr.success(result);
this.router.navigate(['main']);
}
/**
* This method is triggered when user clicks log-in, it calls the aunthenication method
* from oauth service.
*
* @return
*/
login() {
this.oauth.authenticateUser(this.form.username.value, this.form.password.value, this.onSuccess.bind(this));
}
ngAfterContentInit() { //here I build my login button instance after init
this.buildLoginButton();
}
/**
* This function builds the login button, imports the ButtonComponent
*
*/
buildLoginButton(){
let data = {
type: "button",
class: "btn btn-primary px-4",
description: this.translate.transform("pages[login_page][login_form][buttons][login]"),
function: "login",
group: this.userForm
}
const inputFactory = this.resolver.resolveComponentFactory(ButtonComponent);
const loginButton = this.login_button.createComponent(inputFactory);
loginButton.instance.group = data.group;
loginButton.instance.type = data.type;
loginButton.instance.class = data.class;
loginButton.instance.description = data.description;
loginButton.instance.callFunction = function(){ //I call parent function using a static method
LoginComponent.executeMethod(data.function);
}
}
static executeMethod(someMethod){ //for my login button this should return this.login()
eval("this."+someMethod+"()");
}
}
为了使按钮实例可见,我将引用添加到我的登录模板中,如下所示:
<div #login></div>
现在我的按钮是可见的,太棒了!但是现在当我点击按钮时:
错误类型错误:this.login 不是 eval 中的函数(在 push../src/app/views/login/login.component.ts.LoginComponent.executeMethod (login.component.ts:225) 中的 eval :1:6 ) 在 Function.push../src/app/views/login/login.component.ts.LoginComponent.executeMethod (login.component.ts:225) 在 ButtonComponent.loginButton.instance.callFunction (login.component.ts:179 ) 在 Object.eval [as handleEvent] (ButtonComponent.html:2) 在 handleEvent (core.js:10251) 在 callWithDebugContext (core.js:11344) 在 Object.debugHandleEvent [as handleEvent] (core.js:11047) 在dispatchEvent (core.js:7710) at core.js:8154 at HTMLButtonElement。(平台-browser.js:988)
如何让我的按钮在父组件中运行该功能,而不是在其自身中查找该功能?我不想改变太多,ButtonComponent
因为我必须制作其他可能会运行其他功能的按钮,这会使其不那么通用。
有一个解决方案说明使用EventEmitter
这个,但我不确定这将如何工作,因为我如何将按钮导入登录组件,包括ts
和html
编辑完整的login.component.html:
<div class="app-body">
<main class="main d-flex align-items-center">
<div class="container center">
<div class="row">
<div class="col-md-8 mx-auto">
<div class="card-group">
<div class="card p-4">
<div class="card-body">
<form [formGroup]="userForm" (submit)="login()">
<h1>{{ 'pages[login_page][login_form][labels][login]' | translate }}</h1>
<p class="text-muted">{{ 'pages[login_page][login_form][labels][sign_in]' | translate }}</p>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="icon-user"></i></span>
</div>
<div #username> </div>
</div>
<div class="input-group mb-4">
<div class="input-group-prepend">
<span class="input-group-text"><i class="icon-lock"></i></span>
</div>
<div #password> </div>
</div>
<div class="row">
<div class="col-6">
<div #login></div>
<!-- <button type="button" class="btn btn-primary px-4" (click)="login()">{{ 'pages[login_page][login_form][buttons][login]' | translate }}</button> -->
</div>
<div class="col-6 text-right">
<div #forgot></div>
<!-- <button type="button" class="btn btn-link px-0">{{ 'pages[login_page][login_form][urls][forgot_password]' | translate }}</button>-->
</div>
</div>
</form>
</div>
</div>
<div class="card text-white bg-primary py-5 d-md-down-none" style="width:44%">
<div class="card-body text-center">
<div>
<h2>{{ 'pages[login_page][sign_up_panel][labels][sign_up]' | translate }}</h2>
<p>{{ 'pages[login_page][sign_up_panel][labels][new_account]' | translate }}</p>
<div #signUp></div>
<!-- <button type="button" class="btn btn-primary active mt-3">{{ 'pages[login_page][sign_up_panel][buttons][register]' | translate }}</button> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
解决方案
在 button.component.ts 中添加此代码
@Output() clickFunctionCalled = new EventEmitter<any>();
callFunction() {
this.clickFunctionCalled.emit();
}
button.template.html 没有变化
在 html 中使用 app-button 组件的位置添加此代码
<app-button (clickFunctionCalled)="callCustomClickFunction($event)"></app-button>
在 login.component.ts 中添加这个
callCustomClickFunction() {
console.log("custom click called in login");
this.login();
}
基本上,从子组件发出 click 事件。捕获父组件中的事件并调用父组件所需的函数。也可以像这样直接调用父组件的函数
<app-button (clickFunctionCalled)="login($event)"></app-button>
当您使用动态组件创建器来创建按钮组件时,您需要执行类似的操作来绑定输出事件
loginButton.instance.clickFunctionCalled.subscribe(data => {
console.log(data);
});
推荐阅读
- azure - 使用 http 在现有 Function App 中添加/删除 Azure 函数
- reactjs - 如何在 Storybook 中添加样式道具作为控件?
- docker - 无法在 AWS Lambda 容器中启动 Chromium,但可以在本地运行
- html - 如何在前两页使用(document.referrer)?
- google-sheets - 通过单个公式对每一行求和
- python - 我该如何解决这个问题?Python cantools关于id的关键错误
- git - 如何使分叉项目保持最新?
- python - “从 keras.utils 导入 to_categorical”中的错误
- reactjs - 移动 Draggable 时,列表顶部会出现很大的间隙,并且会奇怪地移动所有内容(React Beautiful DND)
- android - 使用光标时出现空指针异常