Angular中為什么不要在模板中調用方法_第1頁
Angular中為什么不要在模板中調用方法_第2頁
Angular中為什么不要在模板中調用方法_第3頁
全文預覽已結束

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

第Angular中為什么不要在模板中調用方法在運行nggeneratecomponentcomponent-name命令后創建angular組件的時候,默認情況下會生成四個文件:

一個組件文件component-name.component.ts

一個模板文件component-name.component.html

一個CSS文件,component-name.component.css

測試文件component-name.component.spec.ts

模板,就是你的HTML代碼,需要避免在里面調用非事件類的方法。舉個例子

!--html模板--

translateName:{{originName}}

translateName:{{getTranslatedName(你好)}}

button(click)=onClick()ClickMe!/button

//組件文件

import{Component}from@angular/core

@Component({

selector:my-app,

templateUrl:./ponent.html,

styleUrls:[./ponent.css],

exportclassAppComponent{

originName=你好

getTranslatedName(name:string):string{

console.log(getTranslatedNamecalledfor,name);

returnhelloworld!

onClick(){

console.log(Buttonclicked!

}

我們在模板里面直接調用了getTranslatedName方法,很方便的顯示了該方法的返回值helloworld。看起來沒什么問題,但如果我們去檢查console會發現這個方法不止調用了一次。

并且在我們點擊按鈕的時候,即便沒想更改originName,還會繼續調用這個方法。

原因與angular的變化檢測機制有關。正常來說我們希望,當一個值發生改變的時候才去重新渲染對應的模塊,但angular并沒有辦法去檢測一個函數的返回值是否發生變化,所以只能在每一次檢測變化的時候去執行一次這個函數,這也是為什么點擊按鈕時,即便沒有對originName進行更改卻還是執行了getTranslatedName

當我們綁定的不是點擊事件,而是其他更容易觸發的事件,例如mouseenter,mouseleave,mousemove等該函數可能會被無意義的調用成百上千次,這可能會帶來不小的資源浪費而導致性能問題。

一個小Demo:

/edit/angular-ivy-4bahvofile=src/app/ponent.html

大多數情況下,我們總能找到替代方案,例如在onInit賦值

import{Component,OnInit}from@angular/core

@Component({

selector:my-app,

templateUrl:./ponent.html,

styleUrls:[./ponent.css],

exportclassAppComponentimplementsOnInit{

originName=你好

TranslatedName:string;

ngOnInit():void{

this.TranslatedName=this.getTranslatedName(this.originName)

getTranslatedName(name:string):string{

console.count(getTranslatedName

retu

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論