Reactive Forms in Angular - Dynamic Validation

Поделиться
HTML-код
  • Опубликовано: 13 июл 2024
  • Learn Everything About Angular Forms 🚀
    bit.ly/advanced-angular-forms_yt
    In this video about Reactive Forms in Angular, I will show you how you can apply and remove validators to certain form controls dynamically, depending on the values from other form controls in your Angular Form. I will show you how to do that using ReactiveForms. You will see which pitfalls you might encounter while implementing this feature and, of course, I will show you how you can overcome them.
    🕒 Time Codes:
    00:00 - Intro
    00:00:55 - Dynamic Validation in Action
    00:11:27 - Promo: Advanced Angular Forms Course
    00:12:53 - Outro;
    💡 Short Frontend Snacks (Tips) every week here:
    Twitter - / decodedfrontend
    Instagram - / decodedfrontend
    LinkedIn - / dmezhenskyi
  • ХоббиХобби

Комментарии • 49

  • @DecodedFrontend
    @DecodedFrontend  Месяц назад +3

    Learn Everything About Angular Forms 🚀
    bit.ly/advanced-angular-forms_yt

  • @rembautimes8808
    @rembautimes8808 Месяц назад +11

    The angular forms course is gold quality. I subscribed last year and helped me a lot in my development

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +7

      I am so happy to hear that! Thank you for sharing your experience!
      P.s. I swear the comment wasn't a paid ad 😅

    • @artempushnev1855
      @artempushnev1855 14 дней назад

      😂​@@DecodedFrontend

  • @ferhado
    @ferhado Месяц назад +3

    I have subscribed to the Angular Forms course. No words, it's just amazing. I highly recommend it to everyone who wants to reach an advanced level in Angular Forms.

  • @nedafayazi
    @nedafayazi Месяц назад

    I wish I could like your Angular Form course million times. Thank you very much for your generusity in teaching complex issues in a very simple way.

  • @MateusBellomo-ml4zm
    @MateusBellomo-ml4zm Месяц назад +3

    I was time travelling here, nice video.

  • @DemystifyFrontend
    @DemystifyFrontend Месяц назад

    You are an awesome guy, love your videos ❤️

  • @Nabulio85
    @Nabulio85 Месяц назад +1

    Thank you Dmytro.
    Great content.
    I have a question about your course. Are you updating its content with the features of the latest versions of Angular? (17 and 18 for example)

  • @ferhado
    @ferhado Месяц назад +2

    Dmytro, could you please make a video about Angular Material theming for v18? The documentation is confusing.

  • @ugochukwuumerie6378
    @ugochukwuumerie6378 Месяц назад +1

    Useful video

  • @syimykamatov8955
    @syimykamatov8955 Месяц назад +1

    Helpfull video

  • @DrCuttler
    @DrCuttler Месяц назад

    Very cool! I actually did the same thing recently, but did it slightly differently:
    a) I added the Validator to the field permanently but enabled and disabled them instead of added and remove them
    b) I transferred the valueChanges observable into a signal and used angular effects for switching.
    BTW: I really enjoy your channel! You made me a better angular developer! :)

  • @madeOfClay99
    @madeOfClay99 Месяц назад

    Top quality content!
    Any plans for making a course all about signals with Angular?
    Thank you for the video Dmytro

  • @arwaromdhane6732
    @arwaromdhane6732 Месяц назад +1

    I want to thank you for your gold videos you helped me a lot ❤❤❤❤❤❤❤❤

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +1

      I'm so glad to hear that! Thank you for the comment :)

  • @JsDevUA
    @JsDevUA Месяц назад +1

    cool 😎

  • @jeffnikelson5824
    @jeffnikelson5824 Месяц назад +4

    Why not use new features like the new control-flow or the takeUntilDestroyed operator

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +2

      Because at the moment when this video was recording, those features were not released :)

  • @koempf
    @koempf Месяц назад +2

    I subscribed to this course also last year :-) great course absolutely :-) would be cool if you could update it to Angular 17/18 features :-) especially Signals :-)

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +2

      Once the signals will be adopted by Angular Forms, I will definitely to the update :)

  • @thanhtuanle7186
    @thanhtuanle7186 Месяц назад

    hey, thanks for your wonderful forms course. How can i get the source code of this video to reference?

  • @RahafHaj
    @RahafHaj Месяц назад +1

    I think using cross validation is better when control validation is related to other control values within the form, where we can get the year value from form.value.year and check it conditionally every time
    conditionalPassportRequired(control: AbstractControl) {
    const {year, passport} = form.value;
    if(year > x && !passport) {
    return {passportRequired: true}
    }
    return null
    }

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +2

      Hi,
      Thanks for your suggestion. As always, in web development, things might be done in many different ways, and each solution has its own pros and cons. Let’s see if the cross-validation at the root FormGroup is indeed a better solution:
      The cross-validator on the root level of the form will invalidate the root FormGroup and not a particular control (passport). This will lead to multiple problems:
      1. Inconsistent error checking. The error object returned by the validator will be added to the root FormGroup.errors. This means that in order to check the passport field against the ‘required’ error, you would need to do it in the root FormGroup like this.form.hasError('passportRequired’). To me, it is quite confusing and not obvious because the error object should “live” in the control it belongs to and not in the root FormGroup.
      2. Inconsistent control validity state. From an Angular point of view, your passport control will remain valid. This means that it will get the ng-valid CSS class. In this case, you might encounter a situation where your field got a green border (indicating a valid state), but below will be displayed an error message that the field is required. This is quite confusing UX.
      3. Scaling. At first glance, this solution wouldn’t scale well. In an actual application, you usually have an object/map like “validatorKey -> Error Message” to keep validation messages consistent across the whole application. Because you introduce a new error key “passportRequired”, you would need to add this key also to the error message map, and the message for this new key should most probably be the same as the message for the regular ‘required’. So if later you would need to change the error message for the “required” validator, you have to update it also for “passportRequired”. And here, we are talking only about the passwordRequired case, but in reality, you might have other dynamic validators, which will make error message management quite challenging.
      4. Performance impact. Most probably, if the validator logic is lightweight and the form is small, you won’t see a real performance impact; however, it is definitely worth mentioning that the validator in the root FormGroup will be triggered every time when any FormControl value changes in the form. It makes no sense to do that because we are interested only in changes from the yearOfbirth control.
      Those are the first thoughts that came to my mind this late night :)

    • @RahafHaj
      @RahafHaj Месяц назад

      That's was great deceleration, thanks 👍

    • @ZawilecxD
      @ZawilecxD 21 день назад

      Hey but what if we assign the validator to the passport FormControl and the change validator code to access "control.parent.year" and return "required" error name :) ?

    • @RahafHaj
      @RahafHaj 20 дней назад

      I think the problem for this is that when we change code control won't trigger the passport validator

  • @vasiliykrush2150
    @vasiliykrush2150 Месяц назад

    For some reason I had expected something better written than what I saw in the video. Like some util. But any case, thanks

  • @cwnhaernjqw
    @cwnhaernjqw Месяц назад +1

    Hi Dmytro nice video. Question: do we also have to unsubscribe onDestroy when subscribing to a form control, or angular takes care of that? Thanks

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +3

      Hi :) Thank you! Honestly, I don't remember that the control models have any mechanism of auto-unsubscription, so I would definitely unsubscribe explicitly. I personally follow the rule - Unsubscribe-Always ;)

  • @andreiarpenti2589
    @andreiarpenti2589 Месяц назад +1

    If user selects 10 times an adult date, won't be the validator added 10 times?
    Or angluar sees that the object is already there, and won't add it many times?

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад

      Good question. This is what says the comment in the src code about that: “Adding a validator that already exists will have no effect” - github.com/angular/angular/blob/101edda0184b458d331163b7e04280c3b8b48bfc/packages/forms/src/model/abstract_model.ts#L788

  • @GamerOfBharat
    @GamerOfBharat Месяц назад +2

    If we do updateValueAndValidity() isn’t it just call the valueChanges() again and again

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад

      Thanks for the question. Yes, updateValueAndValidity() will trigger the valueChanges and statusChanges events. Whether it is a desired behavior or not depends on your particular use case. Nevertheless, if you don't want those events to be emitted, you can call it like this: updateValueAndValidity({ emitEvent: false })

  • @vim2741
    @vim2741 Месяц назад

    upload the course in udemy pls

  • @rockenOne
    @rockenOne Месяц назад

    Use toSignal instead

  • @qdp684
    @qdp684 Месяц назад

    Why not just create a validator for a form?

  • @marcwinner567
    @marcwinner567 2 дня назад

    Is assigning that Validator reference to a local variable for minLength really the "official" way of doing it? I think it would be more cohesive to have some sort of option for it in the method call add/removeValidators. Slava Ukraini!

  • @pavlokozachuk555
    @pavlokozachuk555 Месяц назад +6

    Once the yearOfBirth control is defined with an initial value, it makes sense to add a required validator to the passport control when it's defined, and not by using the startsWith operator.
    Слава Україні!

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +4

      Героям слава 🇺🇦 Yes, it could be an option as well 👍

  • @tarquin161234
    @tarquin161234 Месяц назад +1

    I'm confused by the assignment to this.skills$. I can't fully see what is being done here as the rest of the file is not shown, but why are you using tap here rather than map? If I'm not mistaken, tap will not return anything, so this.skills$ will never emit anything. I also can't see where the subscriptions to this.skills$ are.

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +1

      Hi,
      thanks for the question. In the context of exactly this lesson, this.skills doesn't play any role. However, to answer your question, I use the tap operator because the code inside performs side effects (new FormControls are registered), and the tap operator is exactly the place where side effects have to happen. The map operator should be a pure function that simply transforms data from A -> B, but that was not the case there.

    • @tarquin161234
      @tarquin161234 Месяц назад

      @@DecodedFrontend It's just weird seeing tap with no other operators in the pipe. I was curious to see it's uses.
      Good video anyway

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад +1

      @@tarquin161234 well, the alternative would be to put logic from tap to the subscribe() callback but from the functional point of view it should be the same and it is mostly a matter of taste. I even saw the thread about this topic on Twitter and opinions were split pretty much equally :)

    • @tarquin161234
      @tarquin161234 Месяц назад

      @@DecodedFrontend sure. But from my pov it's confusing because you can't see any subscriptions so looks like the tap will never execute

    • @DecodedFrontend
      @DecodedFrontend  Месяц назад

      Ah, ok. Now I see what confuses you. Actually, the subscription to this.skills$ happens via the async pipe in the template. This will trigger an HTTP call inside the getSkills() method, and once data arrives, it goes to the tap operator where, based on returned data, I create corresponding FormControls and add them to the form (calling buildSkillControls()). Because buildSkillControls() performs side effects, I placed it in the tap operator because, in my case (since I subscribe via async pipe), the tap operator is the only place where I could handle side effects.
      I hope now it is clearer :) It might look strange because you don't know the context of the course and what was done before :)