1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Why property A is called when ngModel is used but not linked to that property A?

Discussão em 'Angular' iniciado por user1169587, Outubro 25, 2024 às 04:52.

  1. user1169587

    user1169587 Guest

    Given the following testing example:

    blank-counter.component.ts

    @Component({
    selector: 'app-blank-counter',
    templateUrl: './blank-counter.component.html',
    styleUrls: ['./blank-counter.component.css']
    })
    export class BlankCounterComponent implements OnInit, OnChanges {
    constructor() { }
    currentDateTime = new Date();
    ngOnInit() {
    console.log('blank counter ngOnInit()');
    }

    ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
    console.log('ngOnChanges, changes:'+changes);
    }

    //@Input()
    _counterValue = 0; // notice the '_'

    get counterValue() {
    console.log('get counterValue()');
    return this._counterValue;
    }
    }


    blank-counter.component.html

    <p>blank-counter works!</p>
    {{counterValue}}
    <p>Input with ngModel:<input type="text" [ngModel]="abc"/></p>
    <p>Input without ngModel:<input type="text" value="abc"/></p>
    <p>Current Date Time:{{currentDateTime}}</p>


    template-driven-form-ex2.component.html

    <p>template-driven-form-ex2 works!</p>
    <app-blank-counter name="blankCounter"></app-blank-counter>


    template-driven-form-ex2.component.ts

    @Component({
    selector: 'app-template-driven-form-ex2',
    templateUrl: './template-driven-form-ex2.component.html',
    styleUrls: ['./template-driven-form-ex2.component.css']
    })
    export class TemplateDrivenFormEx2Component implements OnInit {

    constructor() { }

    ngOnInit() {
    }


    }

    1. If I type some text in

    <p>Input without ngModel:<input type="text" value="abc"/></p>


    get counterValue() is not called, but if I type some text in

    <p>Input with ngModel:<input type="text" [ngModel]="abc"/></p>


    get counterValue() is called, why?
    I know [ngModel] cause template flow to component ts to copy the value to component property "abc" (although no this property defined in component), but why get counterValue() is also called? is it due to the blank-counter.component.html is refreshed?


    1. I found the ngOnchanges is not called even I type something in the textbox with [ngModel], why?


    2. Also, when I type some text in the textbox with [ngModel], get counterValue() is called, then why

    currentDateTime = new Date();


    is not called? As I see the value of {{currentDateTime}} is never changed.

    Continue reading...

Compartilhe esta Página