1758613443
2025-09-23 07:30:00
templatesテンプレート内のバイナリ割り当て演算子 – 最終的に!
Angular 20.1.0で最も話題になっている機能は、コンポーネントテンプレートに直接バイナリ割り当て演算子を導入することです。これ以上の冗長なメソッドは、単純な操作を必要としません!
新着情報?
コンパイラは、テンプレートの割り当て演算子をサポートするようになりました。
Angular 20.1.0の前:
// component.ts
export class CounterComponent {
counter = signal(0);increment() {
this.counter.set(this.counter() + 1);
}
decrement() {
this.counter.set(this.counter() - 1);
}
}
{{ counter() }}
Angular 20.1.0の後:
// component.ts - Much cleaner!
export class CounterComponent {
counter = signal(0);
}
{{ counter() }}
実世界の例:ショッピングカート
ショッピングカートシナリオでこれらのオペレーターを使用する方法は次のとおりです。
export class ShoppingCartComponent {
items = signal([
{ id: 1, name: 'Laptop', price: 999, quantity: 1 },
{ id: 2, name: 'Mouse', price: 29, quantity: 2 }
]);total = computed(() =>
this.items().reduce((sum, item) => sum + (item.price * item.quantity), 0)
);
}
{{ item.name }} - ${{ item.price }}
{{ item.quantity }}
Total: ${{ total() }}
単体試験バイナリ割り当て演算子
これらの新機能を適切にテストする方法は次のとおりです。
describe('ShoppingCartComponent', () => {
let component: ShoppingCartComponent;
let fixture: ComponentFixture;beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ShoppingCartComponent]
}).compileComponents();
fixture = TestBed.createComponent(ShoppingCartComponent);
component = fixture.componentInstance;
});
it('should increment item quantity using += operator', () => {
// Arrange
const initialQuantity = component.items()[0].quantity;
// Act - Simulate button click that uses += operator
const incrementButton = fixture.debugElement.query(
By.css('button:not([disabled])')
);
incrementButton.nativeElement.click();
fixture.detectChanges();
// Assert
expect(component.items()[0].quantity).toBe(initialQuantity + 1);
});
it('should apply discount using ??= operator', () => {
// Arrange
const item = component.items()[0];
expect(item.discount).toBeUndefined();
// Act
const discountButton = fixture.debugElement.query(
By.css('button:contains("Apply 10% Discount")')
);
discountButton.nativeElement.click();
fixture.detectChanges();
// Assert
expect(item.discount).toBe(0.1);
// Test that ??= doesn't overwrite existing values
discountButton.nativeElement.click();
fixture.detectChanges();
expect(item.discount).toBe(0.1); // Should still be 0.1, not changed
});
});
simpleシンプルなテンプレート操作の方法を作成することに不満を感じていますか?コメントで、これらの新しいオペレーターをどのように使用するかを教えてください!
#Angular #20.1.0の完全なガイド開発ワークフローを変換する新機能 #Rajat #9月2025年