
您可以在30秒或更短的時間內可以理解的有用角片段的策劃集合。
初學者摘要
中間片段
高級片段
枚舉很棒,但默認情況下在角模板中看不到它們。有了這個小技巧,您可以使它們可以訪問。
enum Animals {
DOG ,
CAT ,
DOLPHIN
}
@ Component ( {
...
} )
export class AppComponent {
animalsEnum : typeof Animals = Animals ;
}
該片段的互動演示| ⬆回到頂部|標籤:枚舉模板
查看Angular備忘單或(替代版本),其中包含在一個地方凝結的許多有用信息。
同樣,在開發角度應用時,Angular Charglist包含的策劃了常見錯誤列表。
https://malcoded.com/Angular-Cheat-sheet/,https://angular.io/guide/guide/cheatsheet,https://angular.io/guide/guide/styleguide
該片段的互動演示| ⬆回到頂部|標籤:提示備忘單
通過運行來調試瀏覽器控制台中的組件狀態:
ng . probe ( $0 ) . componentInstance
$0是當前在開發工具中選擇的DOM節點(前一個$1,依此類推)。
使用常春藤渲染器引擎:
ng . getComponent ( $0 ) https://blog.angularindepth.com/everything-you-need-to-noc-about-debugging-angular-applications-d308ed8a51b4
該片段的互動演示| ⬆回到頂部|標籤:知名技巧
如果您使用的是與默認值不同的ViewEncapsulation值,則可以為每個組件手動設置該值可能令人生畏。
幸運的是,您可以在引導應用程序時將其配置為全球:
platformBrowserDynamic ( ) . bootstrapModule ( AppModule , [
{
// NOTE: Use ViewEncapsulation.None only if you know what you're doing.
defaultEncapsulation : ViewEncapsulation . None
}
] ) ;
該片段的互動演示| ⬆回到頂部|標籤:配置樣式
要採取刷卡,平底鍋和針刺以及其他移動手勢,您可以將hammerjs與HostListener Decorator一起使用,或者是綁定的事件,
npm install hammerjs@ HostListener ( 'swiperight' )
public swiperight ( ) : void {
// Run code when a user swipes to the right
}這是有關如何使用所有hammerjs事件綁定的示例,您也可以將這些事件與HostListener一起使用:
<!-- pan events -->
< div (pan) =" logEvent($event) " > </ div >
< div (panstart) =" logEvent($event) " > </ div >
< div (panmove) =" logEvent($event) " > </ div >
< div (panend) =" logEvent($event) " > </ div >
< div (pancancel) =" logEvent($event) " > </ div >
< div (panleft) =" logEvent($event) " > </ div >
< div (panright) =" logEvent($event) " > </ div >
< div (panup) =" logEvent($event) " > </ div >
< div (pandown) =" logEvent($event) " > </ div >
<!-- pinch events -->
< div (pinch) =" logEvent($event) " > </ div >
< div (pinchstart) =" logEvent($event) " > </ div >
< div (pinchmove) =" logEvent($event) " > </ div >
< div (pinchend) =" logEvent($event) " > </ div >
< div (pinchcancel) =" logEvent($event) " > </ div >
< div (pinchin) =" logEvent($event) " > </ div >
< div (pinchout) =" logEvent($event) " > </ div >
<!-- press events -->
< div (press) =" logEvent($event) " > </ div >
< div (pressup) =" logEvent($event) " > </ div >
<!-- rotate events -->
< div (rotate) =" logEvent($event) " > </ div >
< div (rotatestart) =" logEvent($event) " > </ div >
< div (rotatemove) =" logEvent($event) " > </ div >
< div (rotateend) =" logEvent($event) " > </ div >
< div (rotatecancel) =" logEvent($event) " > </ div >
<!-- swipe events -->
< div (swipe) =" logEvent($event) " > </ div >
< div (swipeleft) =" logEvent($event) " > </ div >
< div (swiperight) =" logEvent($event) " > </ div >
< div (swipeup) =" logEvent($event) " > </ div >
< div (swipedown) =" logEvent($event) " > </ div >
<!-- tap event -->
< div (tap) =" logEvent($event) " > </ div > https://github.com/angular/angular/blob/master/packages/platform-browser/src/src/src/src/src/events/hammer_gestures.ts ,, http://hammerjs.github.io/api/api/api/papi/papi/papi/papi/papi/#hammer.manager.manager.manager,https:/
該片段的互動演示| ⬆回到頂部|標籤:知識的提示組件手勢
您可以創建自己的輔助組件並使用它代替*ngIf 。
@ Component ( {
selector : 'loader' ,
template : `
<ng-content *ngIf="!loading else showLoader"></ng-content>
<ng-template #showLoader>? Wait 10 seconds!</ng-template>
`
} )
class LoaderComponent {
@ Input ( ) loading : boolean ;
}用於用法示例:
< loader [loading] =" isLoading " > ? ? ? </ loader >請注意,將對內容進行熱切評估,例如,在加載啟動之前,將在下面的片段中創建
destroy-the-world摘要:
< loader [loading] =" isLoading " > < destroy-the-world > </ destroy-the-world > </ loader > https://medium.com/claritydesignsystem/ng-content-the-hidden-hidden-docs-96a29d70d11b,https://blog.angularindepth.com/https-medium-com-com-com-com-com-com-com-thomasburleson-animiman-animimated-ghosts-ghosts-bfc045a51fba
該片段的互動演示| ⬆回到頂部|標籤:提示知識的組件模板
使用ng-content您可以將任何元素傳遞給組件。這簡化了創建可重複使用的組件。
@ Component ( {
selector : 'wrapper' ,
template : `
<div class="wrapper">
<ng-content></ng-content>
</div>
` ,
} )
export class Wrapper { } < wrapper >
< h1 > Hello World! </ h1 >
</ wrapper > https://medium.com/p/96a29d70d11b
該片段的互動演示| ⬆回到頂部|標籤:知識的提示組件
*ngIf指令還支持else聲明。
< div *ngIf =" isLoading; else notLoading " > loading... </ div >
< ng-template #notLoading > not loading </ ng-template >
該片段的互動演示| ⬆回到頂部|標籤:NGIF模板
使用矩陣參數導航:
路由器將導航到/first;name=foo/details
< a [routerLink] =" ['/', 'first', {name: 'foo'}, 'details'] " >
link with params
</ a > https://stackblitz.com/edit/angular-xvy5pd
該片段的互動演示| ⬆回到頂部|標籤:路由
在某些情況下, @Input和@Output屬性的命名與實際輸入和輸出的命名可以不同。
< div
pagination
paginationShowFirst =" true "
(paginationPageChanged) =" onPageChanged($event) " >
</ div > @ Directive ( { selector : '[pagination]' } )
class PaginationComponent {
@ Input ( 'paginationShowFirst' )
showFirst : boolean = true ;
@ Output ( 'paginationPageChanged' )
pageChanged = new EventEmitter ( ) ;
}注意:明智地使用此內容,請參閱styleGuide建議
https://angular.io/guide/styleguide#style-05-13
該片段的互動演示| ⬆回到頂部|標籤:組件模板
安全的導航操作員有助於防止組件模板表達式中的無效異常。如果存在或否則,它將返回對象屬性值,否則將返回。
< p > I will work even if student is null or undefined: {{student?.name}} </ p >{{a?.b?.c}} 下面將被編譯為。
(_co.a == null)? null: ((_co.a.b == null)? null: _co.a.b.c));角/角#791
該片段的互動演示| ⬆回到頂部|標籤:對象屬性處理提示很好
為了避免昂貴的操作,我們可以幫助Angular跟踪添加或刪除的項目,即通過向Ngforof提供TrackBy選項來自定義默認跟踪算法。
因此,您可以提供自定義跟踪功能,該功能將返回每個迭代項目的唯一標識符。例如,該項目的一些關鍵值。如果此鍵值與上一個匹配,則Angular將無法檢測更改。
Trackby採用一個具有索引和項目args的函數。
@ Component ( {
selector : 'my-app' ,
template : `
<ul>
<li *ngFor="let item of items; trackBy: trackByFn">{{item.id}}</li>
</ul>
`
} )
export class AppComponent {
trackByFn ( index , item ) {
return item . id ;
}
}如果給出了TrackBy,則角跟踪會隨函數的返回值而變化。
現在,當您更改集合時,Angular可以根據唯一標識符跟踪已添加或刪除的項目,並創建/破壞僅更改的項目。
https://angular.io/api/common/ngforof ,https://angular.io/api/core/core/trackbyfunction
該片段的互動演示| ⬆回到頂部|標籤:知名技巧組件的性能
在引擎蓋角下,將結構指令彙編成ng-template元素,例如:
<!-- This -->
< div *ngFor =" let item of [1,2,3] " >
<!-- Get expanded into this -->
< ng-template ngFor [ngForOf] =" [1,2,3] " let-item =" $implicit " > </ ng-template >傳遞給 *ngfor指令的值是使用microsyntax編寫的。您可以在文檔中了解它。
還可以查看一個交互式工具,該工具顯示了Alexey Zuev的擴展
https://angular.io/guide/structural-directures#microsyntax,https://alexzuza.github.io/ng-structural-directive-directive-expander/,https://gh/angular.io/guide/guide/guide/guide/guide/guide/guide/structural-directures-directiver-directives#inside-ngfor
該片段的互動演示| ⬆回到頂部|標籤:尖端結構指令微詞法
有時,我們需要使用每個控件的工作形式。這是可以做到的:
function flattenControls ( form : AbstractControl ) : AbstractControl [ ] {
let extracted : AbstractControl [ ] = [ form ] ;
if ( form instanceof FormArray || form instanceof FormGroup ) {
const children = Object . values ( form . controls ) . map ( flattenControls ) ;
extracted = extracted . concat ( ... children ) ;
}
return extracted ;
}示例使用:
// returns all dirty abstract controls
flattenControls ( form ) . filter ( ( control ) => control . dirty ) ;
// mark all controls as touched
flattenControls ( form ) . forEach ( ( control ) =>
control . markAsTouched ( { onlySelf : true } ) ) ; https://angular.io/guide/Reactive-forms
該片段的互動演示| ⬆回到頂部|標籤:反應性形式的提示很好
在模板中添加鍵盤快捷鍵真的很容易:
< textarea (keydown.ctrl.enter) =" doSomething() " > </ textarea > < input (keydown.enter) =" ... " >
< input (keydown.a) =" ... " >
< input (keydown.esc) =" ... " >
< input (keydown.shift.esc) =" ... " >
< input (keydown.control) =" ... " >
< input (keydown.alt) =" ... " >
< input (keydown.meta) =" ... " >
< input (keydown.9) =" ... " >
< input (keydown.tab) =" ... " >
< input (keydown.backspace) =" ... " >
< input (keydown.arrowup) =" ... " >
< input (keydown.shift.arrowdown) =" ... " >
< input (keydown.shift.control.z) =" ... " >
< input (keydown.f4) =" ... " > https://alligator.io/angular/binding-keyup-keydown-vents
該片段的互動演示| ⬆回到頂部|標籤:提示知識
每個渲染的角組件都包裹在主機元素中(與組件的選擇器相同)。
可以使用@HostBinding裝飾器綁定主機元素的屬性和屬性,例如
import { Component , HostBinding } from '@angular/core' ;
@ Component ( {
selector : 'my-app' ,
template : `
<div>Use the input below to select host background-color:</div>
<input type="color" [(ngModel)]="color">
` ,
styles : [
`:host { display: block; height: 100px; }`
]
} )
export class AppComponent {
@ HostBinding ( 'style.background' ) color = '#ff9900' ;
}
該片段的互動演示| ⬆回到頂部|標籤:組件
通常,我們根據整個應用程序獲得一個服務實例。也可以創建每個組件或指令的服務實例。
@ Component ( {
selector : 'provide' ,
template : '<ng-content></ng-content>' ,
providers : [ Service ]
} )
export class ProvideComponent { } @ Directive ( {
selector : '[provide]' ,
providers : [ Service ]
} )
export class ProvideDirective { } https://angular.io/guide/hierarchical-depertincy-injoction#component-level-injectors,https://stackblitz.com/edit/angular/angular-cdk-happy-animals
該片段的互動演示| ⬆回到頂部|標籤:提示組件依賴性注入
可以通過HostListener在組件/指令中添加全局事件偵聽器。一旦您的指示被銷毀後,Angular將會訂閱。
@ Directive ( {
selector : '[rightClicker]'
} )
export class ShortcutsDirective {
@ HostListener ( 'window:keydown.ArrowRight' )
doImportantThings ( ) {
console . log ( 'You pressed right' ) ;
}
}您可以具有多個綁定:
@ HostListener ( 'window:keydown.ArrowRight' )
@ HostListener ( 'window:keydown.PageDown' )
next ( ) {
console . log ( 'Next' )
}您也可以傳遞參數:
@ HostListener ( 'window:keydown.ArrowRight' , '$event.target' )
next ( target ) {
console . log ( 'Pressed right on this element: ' + target )
}
該片段的互動演示| ⬆回到頂部|標籤:事件組件
有時您需要訪問全球document 。
為了簡化單位測試,Angular通過依賴注入提供了:
import { DOCUMENT } from '@angular/common' ;
import { Inject } from '@angular/core' ;
@ Component ( {
selector : 'my-app' ,
template : `<h1>Edit me </h1>`
} )
export class AppComponent {
constructor ( @ Inject ( DOCUMENT ) private document : Document ) {
// Word with document.location, or other things here....
}
} https://angular.io/api/common/document
該片段的互動演示| ⬆回到頂部|標籤:依賴注入
這是通知用戶有非valid值的字段的方法。
markFieldsAsTouched函數formGroup或formarray作為參數。
function markFieldsAsTouched ( form : AbstractControl ) : void {
form . markAsTouched ( { onlySelf : true } ) ;
if ( form instanceof FormArray || form instanceof FormGroup ) {
Object . values ( form . controls ) . forEach ( markFieldsAsTouched ) ;
}
}查看更多通用方法,訪問Kiba的所有嵌套形式控件以使用控件。
https://angular.io/guide/Reactive-forms
該片段的互動演示| ⬆回到頂部|標籤:反應性形式驗證提示很擅長
用於@Output的EventEmitters只是具有EMIT方法的可觀察到的。
這意味著您可以使用Observable實例,例如,我們可以直接連接FormControl值直接更改:
readonly checkbox = new FormControl ( ) ;
@ Output ( ) readonly change = this . checkbox . valueChanges ;
該片段的互動演示| ⬆回到頂部|標籤:提示輸出
可以將模板作為@Input組件來自定義渲染
@ Component ( {
template : `
<nav>
<ng-container *ngTemplateOutlet="template"></ng-container>
</nav>
` ,
} )
export class SiteMenuComponent {
@ Input ( ) template : TemplateRef < any > ;
} < site-menu [template] =" menu1 " > </ site-menu >
< ng-template #menu1 >
< div > < a href =" # " > item1 </ a > </ div >
< div > < a href =" # " > item2 </ a > </ div >
</ ng-template >注意:在大多數情況下應使用
ng-content,並且更簡單,更聲明。僅當您需要使用ng-content無法實現的額外靈活性時,才使用這種方法。
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet
該片段的互動演示| ⬆回到頂部|標籤:模板
默認情況下,Angular將模板中的所有空格帶以節省字節。通常這是安全的。
對於極少數情況,當您需要保留空間時,您可以使用特殊的ngPreserveWhitespaces屬性:
< div ngPreserveWhitespaces >
(___()'`;
/, /`
jgs \"--\
</ div >您還可以在組件上使用PreserveWhitespaces選項。
https://twitter.com/mgechev/status/1108913389277839360
該片段的互動演示| ⬆回到頂部|標籤:提示
重複使用代碼的最佳方法是創建組件,但也可以在模板中進行。
為此,您可以將ng-template與*ngTemplateOutlet指令一起使用。
< p >
< ng-container *ngTemplateOutlet =" fancyGreeting " > </ ng-container >
</ p >
< button >
< ng-container *ngTemplateOutlet =" fancyGreeting " > </ ng-container >
</ button >
< ng-template #fancyGreeting >
Hello < b > {{name}}! </ b >
</ ng-template > https://angular.io/api/common/ngtemplateoutlet,https://angular.io/guide/Structural-directures-directives#the-ng-template
該片段的互動演示| ⬆回到頂部|標籤:模板
如果您需要一個自定義pipe ,則在創建一條管道之前,請考慮檢查已插入自定義管道70多個的NGX管道軟件包。
這裡有一些例子:
< p > {{ date | timeAgo }} </ p >
<!-- Output: "last week" -->
< p > {{ 'foo bar' | ucfirst }} </ p >
<!-- Output: "Foo bar" -->
< p > 3 {{ 'Painting' | makePluralString: 3 }} </ p >
<!-- Output: "3 Paintings" -->
< p > {{ [1, 2, 3, 1, 2, 3] | max }} </ p >
<!-- Output: "3" --> https://github.com/danrevah/ngx-pipes
該片段的互動演示| ⬆回到頂部|標籤:提示管庫
您可以根據組件屬性值使用高級屬性綁定來設置特定樣式值:
< p [style.background-color] =" 'green' " >
I am in green background
</ p >
< p [style.font-size.px] =" isImportant ? '30' : '16' " >
May be important text.
</ p > <!-- Width in pixels -->
< div [style.width.px] =" pxWidth " > </ div >
<!-- Font size in percentage relative to the parent -->
< div [style.font-size.%] =" percentageSize " > ... </ div >
<!-- Height relative to the viewport height -->
< div [style.height.vh] =" vwHeight " > </ div >
該片段的互動演示| ⬆回到頂部|標籤:樣式
類似於如何雙向綁定[(ngModel)]您可以在組件上進行雙向綁定自定義屬性,例如[(value)] 。要使用適當的輸入/輸出命名:
@ Component ( {
selector : 'super-input' ,
template : `...` ,
} )
export class AppComponent {
@ Input ( ) value : string ;
@ Output ( ) valueChange = new EventEmitter < string > ( ) ;
}然後,您可以將其用作:
< super-input [(value)] =" value " > </ super-input >
該片段的互動演示| ⬆回到頂部|標籤:尖端綁定
在應用程序啟動之前,可以使用APP_INITIALIZER令牌在應用程序開始之前執行異步任務。
@ NgModule ( {
providers : [
{
provide : APP_INITIALIZER ,
useValue : functionReturningPromise
multi : true
} ,
} )
export class AppModule { }
https://hackernoon.com/hook-into-ingular-initialization-process-add41a6b7e,https://angular.io/api/api/core/core/app_initializer
該片段的互動演示| ⬆回到頂部|標籤:提示
為了測試目的,您可能需要在組件中註入window.location對象。您可以通過Angular提供的自定義InjectionToken機制來實現這一目標。
export const LOCATION_TOKEN = new InjectionToken < Location > ( 'Window location object' ) ;
@ NgModule ( {
providers : [
{ provide : LOCATION_TOKEN , useValue : window . location }
]
} )
export class SharedModule { }
//...
@ Component ( {
} )
export class AppComponent {
constructor (
@ Inject ( LOCATION_TOKEN ) public location : Location
) { }
} https://itnext.io/testing-browser-window-location-in-angular-application-e4e8388508ff,https://angular.io/guide/guide/depportency/depportency-indoction
該片段的互動演示| ⬆回到頂部|標籤:依賴項注入測試
可以使用@ViewChild (還@ViewChildren和@ContentChild/Children )使用依賴項注入查詢不同類型的組件。
在下面的示例中,我們可以使用@ViewChildren(Base)獲取Foo和Bar的實例。
abstract class Base { }
@ Component ( {
selector : 'foo' ,
providers : [ { provide : Base , useExisting : Foo } ]
} )
class Foo extends Base { }
@ Component ( {
selector : 'bar' ,
providers : [ { provide : Base , useExisting : Bar } ]
} )
class Bar extends Base { }
// Now we can require both types of components using Base.
@ Component ( { template : `<foo></foo><bar></bar>` } )
class AppComponent {
@ ViewChildren ( Base ) components : QueryList < Base > ;
} https://www.youtube.com/watch?v=prrgo6f0cjs
該片段的互動演示| ⬆回到頂部|標籤:知識的提示組件依賴性注入
Angular允許我們控制模塊預加載的方式。
@Angular/Router提供了兩種策略: PreloadAllModules和NoPreloading 。默認情況下啟用了後者,僅按需預加載懶惰模塊。
我們可以通過提供自定義預加載策略來覆蓋這種行為:在下面的示例中,如果連接良好,則所有內容都包括模塊。
import { Observable , of } from 'rxjs' ;
export class CustomPreloading implements PreloadingStrategy {
public preload ( route : Route , load : ( ) => Observable < any > ) : Observable < any > {
return preloadingConnection ( ) ? load ( ) : of ( null ) ;
}
}
const routing : ModuleWithProviders = RouterModule . forRoot ( routes , {
preloadingStrategy : CustomPreloading
} ) ;請注意,上面的示例對於較大的應用程序來說不是很有效,因為它將預緊所有模塊。
https://angular.io/api/router/preloadingstrategy,https://vsavkin.com/angular-router-preloading-modules-modules-ba3c75e424cb,https://medium.com/medium.com/@adrianfaci u/custom-preloading-strategy-for-angular-modules-b3b5c873681a,https://coryrylan.com/blog/custom-preloading-and-preloading-and-lazy-lazy-loading-loading-strategies-with-angular
該片段的互動演示| ⬆回到頂部|標籤:路由器
可以在角度組件中使用SVG標籤,創建美麗的圖形和可視化。您需要知道三件事:
attr < circle [attr.cx] =" x " [attr.cy] =" y " > </ circle >// Not: < child-component > </ child-component >
< g child-component > </ g > @ Component ( { selector : '[child-component]' } )@ Component ( {
selector : '[child-component]' ,
template : `<svg:circle></svg:circle>`
} )
該片段的互動演示| ⬆回到頂部|標籤:提示SVG