Angular 在版本升級16,加入了幾個項目
1. Signals 擺脫zone.js偵測
2. Rxjs新的運算子takeUntilDestroyed
3. Server-side rendering and hydration enhanced 伺服器渲染模式優化
4. 推standalone處理模式,讓所有元件 管道 directives 解耦
5. 開發配置Vite 為預設項目- 超快編譯
6. Autocomplete imports in templates
7. Required inputs → Input可以被設為必填項目!
8. 自閉標籤
其中signals當中我覺得computed最實用,雖然其他框架已經都有類似的
不過對於需要轉型或計算,原本都只能透過管道或是在都先處理完在塞到樣板當中,多了一種方式可用
以下使用範例:
@Component({
selector: 'my-app',
standalone: true,
template: `
{{ fullName() }} <button (click)="setName('John')">Click</button>
`,
})
export class App {
firstName = signal('Jane');
lastName = signal('Doe');
fullName = computed(() => `${this.firstName()} ${this.lastName()}`);
constructor() {
effect(() => console.log('Name changed:', this.fullName()));
}
setName(newName: string) {
this.firstName.set(newName);
}
}
Zone.js 可選設置Configure Zone.js
bootstrapApplication(App, {
providers: [provideZoneChangeDetection({ eventCoalescing: true })]
});
應Signal 新增RxJS interoperability,不過只能夠在建構式階段使用
import { toObservable, signal } from '@angular/core/rxjs-interop';
@Component({...})
export class App {
count = signal(0);
count$ = toObservable(this.count);
ngOnInit() {
this.count$.subscribe(() => ...);
}
}
2. Rxjs新的運算子takeUntilDestroyed
原本常用銷毀訂閱方式
destroy$ = new Subject<any>();
data$ = http.get('...').pipe(takeUntil(this.destroy$));
ngOnDestroy() {
this.destroy$.next(null);
this.destroy$.complete();
}
改成如果在建構式階段
constructor(){
http.get('…').pipe(takeUntilDestroyed()).subscribe(() => ...);
}
建構式以外的週期使用
private _destroyRef = inject(DestroyRef);
ngOnInit() {
http.get('…').pipe(
takeUntilDestroyed(this._destroyRef)
).subscribe(() => ...);
}
import {
bootstrapApplication,
provideClientHydration,
} from '@angular/platform-browser';
...
bootstrapApplication(RootCmp, {
providers: [provideClientHydration()]
});
// 專案遷移
ng generate @angular/core:standalone
// 起專案
ng new --standalone
Tailwind support in esbuild builder · Issue #24752 · angular/angular-cli (github.com)
"builder": "@angular-devkit/build-angular:browser-esbuild"
// 專案遷移
ng generate @angular/core:standalone
// 起專案
ng new --standaloneular:browser-esbuild\",\n...
6. Autocomplete imports in templates
這點倒是真的蠻方便,很多組件都有必填參數,多了這個可以減少忘記給參數的情況
@Component(...) export class App {
@Input({ required: true }) title: string = '';
}
以往
<super-duper-long-component-name [prop]="someVar"></super-duper-long-component-name>
現在簡化
<super-duper-long-component-name [prop]="someVar"/>