我應該在Angular的類中編寫方法作為箭頭函數在Angular中,在技術上可以將類方法編寫為ES2015箭頭函數,但我從未真正見過有人這樣做過。以這個簡單的組件為例:@Component({
selector: 'sample'})export class SampleComponent {
arrowFunction = param => {
// Do something
};
normalFunction(param) {
// Do something
}}這沒有任何問題。有什么不同嗎?為什么我應該或不應該使用它?
3 回答

BIG陽
TA貢獻1859條經驗 獲得超6個贊
類箭頭函數的一個很好的用例是當你想將一個函數傳遞給另一個組件并在函數中保存當前組件的上下文時。
@Component({ template:` I'm the parent <child-component></child-component> `})export class PerentComponent{ text= "default text" arrowFunction = param => { // Do something // let's update something in parent component ( this) this.text = "Updated by parent, but called by child" };}@Component({ template:` I'm the child component `})export class ChildComponent{ @Input() parentFunction; ngOnInit(){ this.parentFunction.() }} <parent-component></parent-component>
在上面的例子中,child
能夠調用父組件的函數并且文本將被正確地更新,就好像我只是將父級更改為:
export class PerentComponent{ text= "default text" arrowFunction (){ this.text = "This text will never update the parent's text property, because `this` will be child component " };}

ibeautiful
TA貢獻1993條經驗 獲得超6個贊
只有一種情況,如果你需要進行AOT編譯,你必須避免使用箭頭功能,如此處所述
配置模塊時,不能使用箭頭功能。
?DONT:
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { Routes, RouterModule } from '@angular/router';@NgModule({ imports: [ BrowserModule, RouterModule, HttpModule, RouterModule.forRoot([], { errorHandler: (err) => console.error(err) }) ], bootstrap: [ AppComponent ], declarations: [ AppComponent ]})export class AppModule {}?做:
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { Routes, RouterModule } from '@angular/router';function errorHandler(err) { console.error(err);}@NgModule({ imports: [ BrowserModule, RouterModule, HttpModule, RouterModule.forRoot([], { errorHandler }) ], bootstrap: [ AppComponent ], declarations: [ AppComponent ]})export class AppModule {}
- 3 回答
- 0 關注
- 1103 瀏覽
添加回答
舉報
0/150
提交
取消