각도 4: 물체의 변화를 관찰하는 방법?
ETA: 나는 변화를 위해 내 폼을 관찰하는 다양한 방법이 있다는 것을 알고 있다.그것은 내가 하려고 하는 것이 아니다.제목이 말해주듯, 나는 물체의 변화를 어떻게 지켜볼 것인지 묻고 있다.아래 나온 앱은 일러스트 용도에 한한다.내가 물어본 질문에 대답해 줘.고마워!
간단한 앱이 있는데
import { Component, OnInit } from '@angular/core';
export class Customer {
firstName: string;
favoriteColor: string;
}
@Component({
selector: 'my-app',
template: `
<div *ngIf="customer">
<input type="text" [(ngModel)]="customer.firstName">
<input type="text" [(ngModel)]="customer.favoriteColor">
</div>
`
})
export class AppComponent implements OnInit {
private customer: Customer;
ngOnInit(): void {
this.customer = new Customer();
// TODO: how can I register a callback that will run whenever
// any property of this.customer has been changed?
}
}
TODO를 참고하십시오. 속성상 항상 실행되는 콜백을 등록해야 함this.customer
바뀌었어
입력에 ngChange를 사용할 수 없다. 나는 모델의 변경사항을 직접 구독해야 한다.그 이유는 나의 사용 사례와 관련이 있고, 여기에 들어갈 가치가 없다.이건 선택사항이 아니라고 믿어줘.
이것이 가능한가?구글링도 많이 해봤는데 말랐어.
각도는 일반적으로 생성자 KeyValueDiffers 클래스에 주입된 것을 사용한다.
당신의 경우 다음과 같이 보일 수 있다.
import { KeyValueChanges, KeyValueDiffer, KeyValueDiffers } from '@angular/core';
export class Customer {
firstName: string;
favoriteColor: string;
}
@Component({
selector: 'my-app',
templateUrl: `./app.component.html`
})
export class AppComponent {
private customerDiffer: KeyValueDiffer<string, any>;
private customer: Customer;
constructor(private differs: KeyValueDiffers) {}
ngOnInit(): void {
this.customer = new Customer();
this.customerDiffer = this.differs.find(this.customer).create();
}
customerChanged(changes: KeyValueChanges<string, any>) {
console.log('changes');
/* If you want to see details then use
changes.forEachRemovedItem((record) => ...);
changes.forEachAddedItem((record) => ...);
changes.forEachChangedItem((record) => ...);
*/
}
ngDoCheck(): void {
const changes = this.customerDiffer.diff(this.customer);
if (changes) {
this.customerChanged(changes);
}
}
}
한 가지 더 많은 옵션은 확인할 속성에 세터를 사용하는 것이다.
참고 항목
나는 모델의 변경사항을 직접 구독해야 한다.
그런 다음 다음 모델 변경 내용을 들어 보십시오.ngModelChange
템플릿:
<input type="text" (ngModelChange)="doSomething($event)" [ngModel]="customer.firstName">
클래스:
doSomething(event) {
console.log(event); // logs model value
}
물체의 변화를 볼 수 없다.각도가 1이 아니잖아. 여기엔 감시자가 없어.또 다른 해결책은 관찰할 수 있는 것들을 통해서일 것이다.
양식을 사용하다
<form #f="ngForm">
<input type="text" name="firstName" [(ngModel)]="customer.firstName">
<input type="text" name="favoriteColor" [(ngModel)]="customer.favoriteColor">
</form>
암호로 되어 있는
@ViewChild('f') f;
ngAfterViewInit() {
this.f.form.valueChanges.subscribe((change) => {
console.log(change)
})
}
사용자 지정 세터를 사용하여 콜백을 트리거할 수 있음:
class Customer {
private _firstName: string
get firstName(): string {
return this._firstName
}
set firstName(firstName: string) {
this.valueChanged(this._firstName, firstName)
this._firstName = firstName
}
private _lastName: string
get lastName(): string {
return this._lastName
}
set lastName(lastName: string) {
this.valueChanged(this._lastName, lastName)
this._lastName = lastName
}
valueChanged: (oldVal, newVal) => void
constructor (valueChanged?: (oldVal, newVal) => void) {
// return an empty function if no callback was provided in case you don't need
// one or want to assign it later
this.valueChanged = valueChanged || (() => {})
}
}
그런 다음 개체를 만들 때 콜백을 할당하십시오.
this.customer = new Customer((oldVal, newVal) => console.log(oldVal, newVal))
// or
this.customer = new Customer()
this.customer.valueChanged = (oldVal, newVal) => console.log(oldVal, newVal)
https://github.com/cartant/rxjs-observe을 방문하십시오.rxjs와 프록시를 기반으로 한다.
import { observe } from "rxjs-observe";
const instance = { name: "Alice" };
const { observables, proxy } = observe(instance);
observables.name.subscribe(value => console.log(name));
proxy.name = "Bob";
우리는 Angular 1.x 앱을 Angular 9로 변환하는 업무를 맡고 있다.ESRI 맵이 있는 어플리케이션이라 ESRI 프레임워크가 테이블로 가져온 몇 가지 깔끔한 도구가 있다.ESRI는 변화를 지켜보는 것 이상의 많은 일을 하는 Utils를 감시한다.
하지만 나는 앵글 1의 간단한 달러 시계를 놓쳤다.게다가, 우리는 우리의 어플리케이션에서 엔티티와 모델을 만들고, 우리는 때때로 이것들을 관찰해야 할지도 모른다.
MappedPropertyClass라는 추상 클래스를 만들었다.지도(Map<string)를 사용하여 클래스 속성을 매핑하므로 ToJ를 쉽게 구현할 수 있다.SON 및 기타 유틸리티 기능.
이 클래스가 가지고 있는 다른 맵은 _propertyChangeMap: Map<string, EventEmitter<{newvalue,oldvalue};
우리는 또한...라는 기능도 가지고 있다.스트링과 콜백 기능이 필요한 $watch.
이 세분류는 기업뿐만 아니라 구성요소 또는 서비스에 의해 확장될 수 있다.
공유하게 되어 기쁘다. 주의할 점은 당신의 재산은 다음과 같아야 한다는 것이다.
public get foo(): string {
return this._get("foo");
}
public set foo(value:string) {
this._set("foo", value);
}
--------------------------------------------------------------------
import { EventEmitter } from '@angular/core';
export abstract class MappedPropertyClass {
private _properties: Map<string, any>;
private _propertyChangeMap: Map<string, EventEmitter<{ newvalue, oldvalue }>>;
protected _set(propertyName: string, propertyValue: any) {
let oldValue = this._get(propertyName);
this._properties.set(propertyName, propertyValue);
this.getPropertyChangeEmitter(propertyName).emit({ newvalue:
propertyValue, oldvalue: oldValue });
}
protected _get(propertyName: string): any {
if (!this._properties.has(propertyName)) {
this._properties.set(propertyName, undefined);
}
return this._properties.get(propertyName);
}
protected get properties(): Map<string, any> {
var props = new Map<string, any>();
for (let key of this._properties.keys()) {
props.set(key, this._properties.get(key));
}
return props;
}
protected constructor() {
this._properties = new Map<string, any>();
this._propertyChangeMap = new Map<string, EventEmitter<{ newvalue: any,
oldvalue: any }>>();
}
private getPropertyChangeEmitter(propertyName: string): EventEmitter<{
newvalue, oldvalue }> {
if (!this._propertyChangeMap.has(propertyName)) {
this._propertyChangeMap.set(propertyName, new EventEmitter<{ newvalue,
oldvalue }>());
}
return this._propertyChangeMap.get(propertyName);
}
public $watch(propertyName: string, callback: (newvalue, oldvalue) => void):
any {
return this.getPropertyChangeEmitter(propertyName).subscribe((results) =>
{
callback(results.newvalue, results.oldvalue);
});
}
}
참조URL: https://stackoverflow.com/questions/46330070/angular-4-how-to-watch-an-object-for-changes
'Programing' 카테고리의 다른 글
각도2 클릭 없이 이벤트를 트리거(클릭)하는 방법 (0) | 2022.03.20 |
---|---|
Vuetify 탭을 Vue-Router와 함께 사용하는 방법 (0) | 2022.03.20 |
Babel과 TypeScript의 주요 차이점 (0) | 2022.03.20 |
MySQLDB라는 모듈 없음 (0) | 2022.03.19 |
Resact의 해당 구성 요소 외부에 있는 버튼에서 양식을 제출하는 방법? (0) | 2022.03.19 |