Angular 7 FormControl on valueChanges get old value












2















I got a formControl passed in @Input parameter that is bounded to input of number type that maximum value should be 10.
When user types number that is bigger it should not change input value.



What is the way to either prevent event propagation or get old value and set it again?



I tried many other solutions from stack and github, but nothing solves my problem.



 valuecontrol: FormControl = new FormControl(0);

constructor(){
this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue=>{
if(newValue >= 10){
// set previous value
const oldValue = this.control.value;
console.log("old value = ", oldValue)
this.control.patchValue(oldValue);
}
})
}.


DEMO: https://stackblitz.com/edit/angular-6ocjfj?file=src/app/app.component.ts










share|improve this question




















  • 1





    Why don't you just set max="10" on the input and set Validators.max(10) on the FormControl, to let the user know that what he typed is invalid? How would your technique work if the rule was that the value must be >=10? How would the user be able to type the 20 if typing 2 set back the value to blank because 2 is smaller than 10? That wouldn't work. Just use validation.

    – JB Nizet
    Nov 25 '18 at 23:58













  • The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get old value

    – Vikas
    Nov 26 '18 at 2:40
















2















I got a formControl passed in @Input parameter that is bounded to input of number type that maximum value should be 10.
When user types number that is bigger it should not change input value.



What is the way to either prevent event propagation or get old value and set it again?



I tried many other solutions from stack and github, but nothing solves my problem.



 valuecontrol: FormControl = new FormControl(0);

constructor(){
this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue=>{
if(newValue >= 10){
// set previous value
const oldValue = this.control.value;
console.log("old value = ", oldValue)
this.control.patchValue(oldValue);
}
})
}.


DEMO: https://stackblitz.com/edit/angular-6ocjfj?file=src/app/app.component.ts










share|improve this question




















  • 1





    Why don't you just set max="10" on the input and set Validators.max(10) on the FormControl, to let the user know that what he typed is invalid? How would your technique work if the rule was that the value must be >=10? How would the user be able to type the 20 if typing 2 set back the value to blank because 2 is smaller than 10? That wouldn't work. Just use validation.

    – JB Nizet
    Nov 25 '18 at 23:58













  • The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get old value

    – Vikas
    Nov 26 '18 at 2:40














2












2








2








I got a formControl passed in @Input parameter that is bounded to input of number type that maximum value should be 10.
When user types number that is bigger it should not change input value.



What is the way to either prevent event propagation or get old value and set it again?



I tried many other solutions from stack and github, but nothing solves my problem.



 valuecontrol: FormControl = new FormControl(0);

constructor(){
this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue=>{
if(newValue >= 10){
// set previous value
const oldValue = this.control.value;
console.log("old value = ", oldValue)
this.control.patchValue(oldValue);
}
})
}.


DEMO: https://stackblitz.com/edit/angular-6ocjfj?file=src/app/app.component.ts










share|improve this question
















I got a formControl passed in @Input parameter that is bounded to input of number type that maximum value should be 10.
When user types number that is bigger it should not change input value.



What is the way to either prevent event propagation or get old value and set it again?



I tried many other solutions from stack and github, but nothing solves my problem.



 valuecontrol: FormControl = new FormControl(0);

constructor(){
this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue=>{
if(newValue >= 10){
// set previous value
const oldValue = this.control.value;
console.log("old value = ", oldValue)
this.control.patchValue(oldValue);
}
})
}.


DEMO: https://stackblitz.com/edit/angular-6ocjfj?file=src/app/app.component.ts







angular angular-reactive-forms angular7






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 11 hours ago









tobias47n9e

1,00531339




1,00531339










asked Nov 25 '18 at 23:36









karoluSkaroluS

691517




691517








  • 1





    Why don't you just set max="10" on the input and set Validators.max(10) on the FormControl, to let the user know that what he typed is invalid? How would your technique work if the rule was that the value must be >=10? How would the user be able to type the 20 if typing 2 set back the value to blank because 2 is smaller than 10? That wouldn't work. Just use validation.

    – JB Nizet
    Nov 25 '18 at 23:58













  • The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get old value

    – Vikas
    Nov 26 '18 at 2:40














  • 1





    Why don't you just set max="10" on the input and set Validators.max(10) on the FormControl, to let the user know that what he typed is invalid? How would your technique work if the rule was that the value must be >=10? How would the user be able to type the 20 if typing 2 set back the value to blank because 2 is smaller than 10? That wouldn't work. Just use validation.

    – JB Nizet
    Nov 25 '18 at 23:58













  • The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get old value

    – Vikas
    Nov 26 '18 at 2:40








1




1





Why don't you just set max="10" on the input and set Validators.max(10) on the FormControl, to let the user know that what he typed is invalid? How would your technique work if the rule was that the value must be >=10? How would the user be able to type the 20 if typing 2 set back the value to blank because 2 is smaller than 10? That wouldn't work. Just use validation.

– JB Nizet
Nov 25 '18 at 23:58







Why don't you just set max="10" on the input and set Validators.max(10) on the FormControl, to let the user know that what he typed is invalid? How would your technique work if the rule was that the value must be >=10? How would the user be able to type the 20 if typing 2 set back the value to blank because 2 is smaller than 10? That wouldn't work. Just use validation.

– JB Nizet
Nov 25 '18 at 23:58















The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get old value

– Vikas
Nov 26 '18 at 2:40





The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get old value

– Vikas
Nov 26 '18 at 2:40












2 Answers
2






active

oldest

votes


















1














The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get the old value.



The best approach would be to use a validator as mentioned by @JB Nizet.



If you want to continue with your solution then you can leverage Angular's ngDoCheck life Cycle Hook to retain the old value.



Modified Code:



export class AppComponent implements DoCheck {
private oldValue;
control: FormControl = new FormControl(0);

constructor() {
this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue => {
if (newValue >= 10) {
// set previous value
console.log("old value = ", this.oldValue)
this.control.patchValue(this.oldValue);
}
})


}
ngDoCheck() {
this.oldValue = this.control.value
}
}



StackBlitz






share|improve this answer


























  • it is working, i will the answer open for now maybe somebody will come up with better solution. Thank you.

    – karoluS
    Nov 28 '18 at 9:46



















0














Set a [max] attribute on the input control to 10:



<input type="number" [max]="10" [formControl]="control">



That way you can remove the newValue >= 10 condition entirely.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473087%2fangular-7-formcontrol-on-valuechanges-get-old-value%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get the old value.



    The best approach would be to use a validator as mentioned by @JB Nizet.



    If you want to continue with your solution then you can leverage Angular's ngDoCheck life Cycle Hook to retain the old value.



    Modified Code:



    export class AppComponent implements DoCheck {
    private oldValue;
    control: FormControl = new FormControl(0);

    constructor() {
    this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue => {
    if (newValue >= 10) {
    // set previous value
    console.log("old value = ", this.oldValue)
    this.control.patchValue(this.oldValue);
    }
    })


    }
    ngDoCheck() {
    this.oldValue = this.control.value
    }
    }



    StackBlitz






    share|improve this answer


























    • it is working, i will the answer open for now maybe somebody will come up with better solution. Thank you.

      – karoluS
      Nov 28 '18 at 9:46
















    1














    The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get the old value.



    The best approach would be to use a validator as mentioned by @JB Nizet.



    If you want to continue with your solution then you can leverage Angular's ngDoCheck life Cycle Hook to retain the old value.



    Modified Code:



    export class AppComponent implements DoCheck {
    private oldValue;
    control: FormControl = new FormControl(0);

    constructor() {
    this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue => {
    if (newValue >= 10) {
    // set previous value
    console.log("old value = ", this.oldValue)
    this.control.patchValue(this.oldValue);
    }
    })


    }
    ngDoCheck() {
    this.oldValue = this.control.value
    }
    }



    StackBlitz






    share|improve this answer


























    • it is working, i will the answer open for now maybe somebody will come up with better solution. Thank you.

      – karoluS
      Nov 28 '18 at 9:46














    1












    1








    1







    The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get the old value.



    The best approach would be to use a validator as mentioned by @JB Nizet.



    If you want to continue with your solution then you can leverage Angular's ngDoCheck life Cycle Hook to retain the old value.



    Modified Code:



    export class AppComponent implements DoCheck {
    private oldValue;
    control: FormControl = new FormControl(0);

    constructor() {
    this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue => {
    if (newValue >= 10) {
    // set previous value
    console.log("old value = ", this.oldValue)
    this.control.patchValue(this.oldValue);
    }
    })


    }
    ngDoCheck() {
    this.oldValue = this.control.value
    }
    }



    StackBlitz






    share|improve this answer















    The valueChanges event is fired after the new value is updated to the FormControl value that's why you are unable to get the old value.



    The best approach would be to use a validator as mentioned by @JB Nizet.



    If you want to continue with your solution then you can leverage Angular's ngDoCheck life Cycle Hook to retain the old value.



    Modified Code:



    export class AppComponent implements DoCheck {
    private oldValue;
    control: FormControl = new FormControl(0);

    constructor() {
    this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue => {
    if (newValue >= 10) {
    // set previous value
    console.log("old value = ", this.oldValue)
    this.control.patchValue(this.oldValue);
    }
    })


    }
    ngDoCheck() {
    this.oldValue = this.control.value
    }
    }



    StackBlitz







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 15 hours ago









    tobias47n9e

    1,00531339




    1,00531339










    answered Nov 26 '18 at 2:53









    VikasVikas

    6,02841738




    6,02841738













    • it is working, i will the answer open for now maybe somebody will come up with better solution. Thank you.

      – karoluS
      Nov 28 '18 at 9:46



















    • it is working, i will the answer open for now maybe somebody will come up with better solution. Thank you.

      – karoluS
      Nov 28 '18 at 9:46

















    it is working, i will the answer open for now maybe somebody will come up with better solution. Thank you.

    – karoluS
    Nov 28 '18 at 9:46





    it is working, i will the answer open for now maybe somebody will come up with better solution. Thank you.

    – karoluS
    Nov 28 '18 at 9:46













    0














    Set a [max] attribute on the input control to 10:



    <input type="number" [max]="10" [formControl]="control">



    That way you can remove the newValue >= 10 condition entirely.






    share|improve this answer






























      0














      Set a [max] attribute on the input control to 10:



      <input type="number" [max]="10" [formControl]="control">



      That way you can remove the newValue >= 10 condition entirely.






      share|improve this answer




























        0












        0








        0







        Set a [max] attribute on the input control to 10:



        <input type="number" [max]="10" [formControl]="control">



        That way you can remove the newValue >= 10 condition entirely.






        share|improve this answer















        Set a [max] attribute on the input control to 10:



        <input type="number" [max]="10" [formControl]="control">



        That way you can remove the newValue >= 10 condition entirely.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 26 '18 at 0:04

























        answered Nov 25 '18 at 23:51









        fuzzfuzz

        15.8k17109186




        15.8k17109186






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473087%2fangular-7-formcontrol-on-valuechanges-get-old-value%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Ottavio Pratesi

            Tricia Helfer

            15 giugno