Reactive Forms in Angular - Dynamic Validation

Тәжірибелік нұсқаулар және стиль

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

Пікірлер: 48

  • @DecodedFrontend
    @DecodedFrontendАй бұрын

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

  • @rembautimes8808
    @rembautimes8808Ай бұрын

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

  • @DecodedFrontend

    @DecodedFrontend

    Ай бұрын

    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

    6 күн бұрын

    😂​@@DecodedFrontend

  • @ferhado
    @ferhadoАй бұрын

    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
    @nedafayazi23 күн бұрын

    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.

  • @Nabulio85
    @Nabulio8526 күн бұрын

    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)

  • @MateusBellomo-ml4zm
    @MateusBellomo-ml4zmАй бұрын

    I was time travelling here, nice video.

  • @DecodedFrontend

    @DecodedFrontend

    Ай бұрын

    Haha, yes :)

  • @DemystifyFrontend
    @DemystifyFrontend26 күн бұрын

    You are an awesome guy, love your videos ❤️

  • @ferhado
    @ferhadoАй бұрын

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

  • @DrCuttler
    @DrCuttler28 күн бұрын

    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! :)

  • @jeffnikelson5824
    @jeffnikelson5824Ай бұрын

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

  • @DecodedFrontend

    @DecodedFrontend

    Ай бұрын

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

  • @ugochukwuumerie6378
    @ugochukwuumerie637828 күн бұрын

    Useful video

  • @arwaromdhane6732
    @arwaromdhane6732Ай бұрын

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

  • @DecodedFrontend

    @DecodedFrontend

    Ай бұрын

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

  • @syimykamatov8955
    @syimykamatov8955Ай бұрын

    Helpfull video

  • @madeOfClay99
    @madeOfClay99Ай бұрын

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

  • @RahafHaj
    @RahafHaj29 күн бұрын

    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

    29 күн бұрын

    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

    28 күн бұрын

    That's was great deceleration, thanks 👍

  • @ZawilecxD

    @ZawilecxD

    13 күн бұрын

    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

    12 күн бұрын

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

  • @koempf
    @koempfАй бұрын

    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

    Ай бұрын

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

  • @thanhtuanle7186
    @thanhtuanle718629 күн бұрын

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

  • @vasiliykrush2150
    @vasiliykrush215028 күн бұрын

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

  • @JsDevUA
    @JsDevUA29 күн бұрын

    cool 😎

  • @cwnhaernjqw
    @cwnhaernjqwАй бұрын

    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

    Ай бұрын

    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
    @andreiarpenti258929 күн бұрын

    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

    29 күн бұрын

    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

  • @vim2741
    @vim274126 күн бұрын

    upload the course in udemy pls

  • @GamerOfBharat
    @GamerOfBharatАй бұрын

    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 })

  • @qdp684
    @qdp684Ай бұрын

    Why not just create a validator for a form?

  • @rockenOne
    @rockenOne26 күн бұрын

    Use toSignal instead

  • @pavlokozachuk555
    @pavlokozachuk555Ай бұрын

    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

    Ай бұрын

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

  • @tarquin161234
    @tarquin16123429 күн бұрын

    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

    29 күн бұрын

    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

    29 күн бұрын

    @@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

    29 күн бұрын

    @@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

    29 күн бұрын

    @@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

    29 күн бұрын

    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 :)

Келесі