Dynamic Component in Angular (2024)

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 ธ.ค. 2024

ความคิดเห็น • 89

  • @DecodedFrontend
    @DecodedFrontend  4 หลายเดือนก่อน +1

    💡 Follow Decoded Frontend also here:
    Join More than 500+ Angular Developers on our Discord Server - bit.ly/decoded-frontend-discord
    Also, follow me on:
    Twitter - twitter.com/DecodedFrontend
    Instagram - instagram.com/decodedfrontend
    LinkedIn - www.linkedin.com/in/dmezhenskyi

  • @MuratZan
    @MuratZan หลายเดือนก่อน +1

    Teşekkürler.

    • @DecodedFrontend
      @DecodedFrontend  หลายเดือนก่อน +1

      Wow! Thank you so much for support ❤️

  • @EtoBARAKUDAvasa
    @EtoBARAKUDAvasa 4 หลายเดือนก่อน +4

    My first experience of dynamic component start at ~3 year ago when add npm module to Angular who doesn't have integration with Angular - its very help me make unic feature and save many times.
    And I recommend make some unic ComponentRendererService with method renderComponent who take (component: Type, inputs: Partial) and return ComponentRef and here you can also control of destroy dynamic components

  • @angular-developer-e1t
    @angular-developer-e1t หลายเดือนก่อน

    Ты реально крут. 6 лет работал с Angualr и не знал этих вещей. Сейчас делаю тестовое задание на динамические формы с самописными импутами и это точно то что мне нужно.

  • @FranklyTerrible
    @FranklyTerrible 2 หลายเดือนก่อน +2

    Dmitry, you are the best Angular source ever.

  • @denisBriceag
    @denisBriceag 3 หลายเดือนก่อน +1

    Hi, Dmitry! Thanks for the video, very explanatory, as always.
    I’ve been using dynamic components together with material stepper. It might be useful when you don’t want to eagerly load all the steps which are separate components with its own business logic.

  • @oleksandrvorovchenko8674
    @oleksandrvorovchenko8674 4 หลายเดือนก่อน +2

    Дякую! Класне пояснення , як завжди!

  • @stepandemchenko9870
    @stepandemchenko9870 4 หลายเดือนก่อน +2

    Is it possible assign directive to dynamic component? For example create dynamic component which was implement of ControlValueAccessor interface and after that assign to this component formControlName directive

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน +2

      Hey! As far as I know, it is not possible to apply directives at runtime. However, I think that something similar you could achieve with Directive Composition API.

  • @farshadbayat64
    @farshadbayat64 4 หลายเดือนก่อน

    How can we dynamically create a ViewContainer? Is it possible to create a ViewContainer using an element that exists in the component or by using the class name?

  • @knoppix20
    @knoppix20 4 หลายเดือนก่อน +2

    Great tutorial! But is it possible to specify component name as string const/variable and then convert/import this string to real object/instance?

    • @fabiangubeli3319
      @fabiangubeli3319 4 หลายเดือนก่อน +1

      Also interested in this question. Currently I use a map from String to Component to solve this

    • @knoppix20
      @knoppix20 4 หลายเดือนก่อน

      Once i tried to made this. Name of class from string to object conversion but webpack builder not allowed to do so as it cant find full real path of component. It need that all component paths before compile process was already fully know but not pieces of this.

  • @SamuelMarsha-v1s
    @SamuelMarsha-v1s 2 หลายเดือนก่อน

    How do you use this pattern with Viewchildren?
    If you have multiple different components that need to be created AfterViewInit for example; such as creating multiple widgets (which could be different components) whose count you don't know beforehand; how would you go about it?

  • @vkiperman
    @vkiperman 4 หลายเดือนก่อน +2

    Another gem of a video!

  • @pointlesspos8440
    @pointlesspos8440 4 หลายเดือนก่อน

    I'v been using ngx-dynamic components for a few years. It's also a nice option. Pair that with gridster and you can do a dashboard.

  • @Tanvir1642
    @Tanvir1642 4 หลายเดือนก่อน +1

    I noticed you didn't add the Dynamic Component in the imports array. So, is it lazily loaded?

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน +1

      No, it is eagerly loaded. For lazy loading, I would need to use import(../path2component…)

  • @Sevkingblade
    @Sevkingblade 4 หลายเดือนก่อน

    Awesome video as always Dmytro!

  • @hobbytsworld
    @hobbytsworld 4 หลายเดือนก่อน +2

    As always top content!

  • @HimanshuGargMusic
    @HimanshuGargMusic 4 หลายเดือนก่อน

    How we can use the composition directive for the component where we form controls and methods that we want to remove its duplicacy and the code can not be used as directive in component, Thanks in advance ❤

  • @TheSysmat
    @TheSysmat 4 หลายเดือนก่อน +4

    Nice video, very good ng content

  • @oleksandrfesiuk6310
    @oleksandrfesiuk6310 4 หลายเดือนก่อน +4

    Дякую за корисний контент!

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน +3

      Дуже дякую за фідбек😊

  • @ytamb01
    @ytamb01 4 หลายเดือนก่อน

    Really enjoyed the video. Thank you. I would be very interested to see a nice implementation of lazy-loading dynamically generated components as part of this series.

    • @andrewg2998
      @andrewg2998 4 หลายเดือนก่อน

      Are you talking about the route based lazy loading they introduced in angular 15 or the deferrable views ?

    • @ytamb01
      @ytamb01 4 หลายเดือนก่อน

      @@andrewg2998 I have been able to do this in ng 18 and it shows a lot of promise for something like a configurable dashboard. I really like the idea of a user being able to configure what components they would like without having to load them in the initial bundle.
      async onLoadComponent() {
      this.viewContainerRef.clear();
      const { MessageComponent } = await import('../message/message.component');
      this.componentRef = this.viewContainerRef.createComponent(MessageComponent);
      if (this.componentRef) {
      this.componentRef.setInput('message', 'this message was set by the dashboard');
      }
      }

    • @ytamb01
      @ytamb01 4 หลายเดือนก่อน

      @@andrewg2998 In ng18 you can do this on a button click:
      async onLoadComponent() {
      this.viewContainerRef.clear();
      const { MessageComponent } = await import('../message/message.component');
      this.componentRef = this.viewContainerRef.createComponent(MessageComponent);
      if (this.componentRef) {
      this.componentRef.setInput('message', 'this message was set by the dashboard');
      }
      }
      I think this would be great on a dashboard where user could select the components they want without loading them in the initial bundle. But I'm not sure what the best pattern for something like this would be. I don't love the async and await here for example.

    • @ytamb01
      @ytamb01 4 หลายเดือนก่อน

      @@andrewg2998 No I meant using import directly e.g. const { MessageComponent } = await import('../message/message.component'); and then this.componentRef = this.viewContainerRef.createComponent(MessageComponent);

  • @vigneshwaran332
    @vigneshwaran332 หลายเดือนก่อน

    great Video, please make one for dynamically creating component with custom Injector

  • @DemystifyFrontend
    @DemystifyFrontend 3 หลายเดือนก่อน +1

    Very well explained 🎉

  • @IvanYermolenkoSS
    @IvanYermolenkoSS หลายเดือนก่อน

    Дякую за корисний контент! 🔥

  • @amrahmed3083
    @amrahmed3083 4 หลายเดือนก่อน +5

    Great video but I think you need to add in what situations would this be helpful and recommended 😊

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน +4

      You’re right, I should have mentioned that. The next video is also about dynamic components and I’ll do it there 😉

    • @amrahmed3083
      @amrahmed3083 4 หลายเดือนก่อน +1

      @@DecodedFrontend sounds great😃❤️

  • @returncode0000
    @returncode0000 4 หลายเดือนก่อน +3

    Very useful content

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน +2

      Thank you! 😊

    • @returncode0000
      @returncode0000 4 หลายเดือนก่อน +1

      @@DecodedFrontend It's useful because you used a very small example/use case so it's understandable and you have a very good speed when explaining, not too fast, so that everyone can follow your explanation 👏 Keep it up! (it is also a topic that I didn't understood well enough, so thanks for this also)

  • @yurtiksupreme465
    @yurtiksupreme465 3 หลายเดือนก่อน +2

    Якби ми користували наприклад @if Statement ? чи є різниця між ними?
    Для чого користувати dynamic component?

    • @DecodedFrontend
      @DecodedFrontend  3 หลายเดือนก่อน +2

      З функціональної точки зору різниці не має. Річ тут скоріше в тому, що рішення з if-ами буде гірше масштабуватись. Якщо ми уявимо, що в нас кілька варіантів віджетів, то в нашому хост-компоненті (компонент в якому створюємо віджети) одразу зʼявиться під кожний варіант свій if, що вже не дуже зручно. Але гірше те, що кожного разу коли треба буде додати новий тип віджету, треба модифікувати хост-компонент, тобто тут порушується open-closed principle, який каже що функціонал компоненту може бути розширеним без його модифікації. Це веде так чи інакше до негативних наслідків при масштабуванні і також тестуванні, бо кожен новий тип віджету треба буде «мокати» і оновлювати тести.
      Резюме:
      if / else добре коли в тебе 1-2 компонента і ти впевнений що: а) це не потрібно масштабувати. б) знаєш наперед з яким компонентом будеш працювати. Приклад: компонент профілю користувача який показується в залежності від того, чи користувач залогінився.
      Dynamic components добре коли в тебе є багато однотипних компонентів і ти впевнений що: а) в майбутньому будуть добавлятись нові типи. б) не зрозуміло наперед який саме компонент треба буде створити. Приклад: створення компонентів (віджетів) з json конфігу який приходить з серверу.
      Ще рекомендую глянути моє крайнє відео також про створення компонентів динамічно, але декларативним підходом. Там в кінці я також показую приклад як би це виглядало в реальному житті - th-cam.com/video/o3I2Eg6Q4LA/w-d-xo.htmlsi=n2A-VcWvct9gudbA

    • @yurtiksupreme465
      @yurtiksupreme465 3 หลายเดือนก่อน +2

      @@DecodedFrontend зрозуміло. Дуже дякую!

  • @hanshans9902
    @hanshans9902 2 หลายเดือนก่อน +1

    thanks. good content😊

  • @jontaylor1586
    @jontaylor1586 4 หลายเดือนก่อน

    I needed this the other day. The fact that you're creating siblings of the element used to make the viewContainerRef threw me way off.

  • @Diamondiam0nd
    @Diamondiam0nd 4 หลายเดือนก่อน

    Hi I feel like I got nobody to ask, but is passing signal inputs through some component a valid pattern? Like I got a parent main component named "A", which has declared some signal value. This component have dumb B component declared inside its html. The B component contains some mini ui component named "C". Is passing a value through signal inputs/outputs from component C to B to A a valid pattern?

    • @codeSurvivor
      @codeSurvivor 4 หลายเดือนก่อน +1

      It is, but if you get more than 2 levels I would use a shared service with that signal, observable or whatever you need to share. This is a common pattern when needing to communicate components that are siblings or deeply nested children

  • @serhiilytvyn8753
    @serhiilytvyn8753 4 หลายเดือนก่อน +1

    Thanks a lot for your videos and good explanation.

  • @bukanaka
    @bukanaka 4 หลายเดือนก่อน +2

    Имба контент подъехал на угловой тачке))

  • @cherepovets8994
    @cherepovets8994 4 หลายเดือนก่อน +2

    Thank you! Great video! But I want to add, that output() is not signal based

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน +1

      Oh, indeed, I said “signal-based outputs” which is wrong. Sorry for the confusion, you are right. Just most of the new APIs like input, ViewChild, etc are signal-based, so that I mapped in my head all these new functions as signal-based too 😅

  • @rifathossain2788
    @rifathossain2788 3 หลายเดือนก่อน +1

    thank you so much, this video was amazing.

  • @ievgensvichkar2643
    @ievgensvichkar2643 3 หลายเดือนก่อน

    I wish working with inputs and outputs of dynamic components was consistent. But instead we have: inputs are set via setInput() API w/o direct access of the class instance, but output is accessed using direct access to the instance

  • @urtaav639
    @urtaav639 4 หลายเดือนก่อน

    excellent video, master how can I create multiple components that is, I have a drop-down list of options when selecting 1, I want to show component1 component2 and component5, when selecting 2 show component2, component3, component8 to say the least, the idea is to show the components without order and That each one is connected to my form, can you do that or what is the topic to investigate it, help master

  • @musoverda
    @musoverda 4 หลายเดือนก่อน +1

    why do you use the # symbol to create a private property?

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน

      Because it is shorter and unlike TypeScript’s” “private” access modifier, the # makes property private even later at runtime.

    • @musoverda
      @musoverda 4 หลายเดือนก่อน

      @@DecodedFrontend do you use the # symbol in your projects? in production?

  • @rkrao8582
    @rkrao8582 4 หลายเดือนก่อน

    Omg as complex as it is, I would only imagine what would happen if try to write tests for this. 🤯 As always great content though

  • @Anonym-mw5lz
    @Anonym-mw5lz 3 หลายเดือนก่อน

    is it somehow possible to lazy load dynamic components?

  • @farshadbayat64
    @farshadbayat64 4 หลายเดือนก่อน +1

    Thank you for this video.

  • @cdotforce
    @cdotforce 3 หลายเดือนก่อน

    Very useful when you need to federate components from a MFE to another one because the client does not provide a components library. That was my case.

  • @qyihamba7034
    @qyihamba7034 2 หลายเดือนก่อน

    I would love for Angular to provide APIs that enable dynamic component creation with directive support. You cannot for example create dynamic forms without any template code. It's very exciting until you have to include formGroup directive

  • @kevinsamuelndoum6992
    @kevinsamuelndoum6992 2 หลายเดือนก่อน

    Thank you so much sir. This video is amazing

  • @o_glethorpe
    @o_glethorpe 4 หลายเดือนก่อน

    Thanks for sharing... Would You be so kind to create a video about service locator? Im trying to implement clean archtecture and want to be able to configure what service some component should use on the start of the application, something like, now the signin component should work with firebase, now with rest api.

  • @DimanIvanov
    @DimanIvanov 3 หลายเดือนก่อน +1

    Awesome!

  • @mohammadrezamrg9380
    @mohammadrezamrg9380 4 หลายเดือนก่อน

    It would be good if making something with server driven ui like angular spartacus storefront

  • @hendjfjfj.hdjfn_h
    @hendjfjfj.hdjfn_h 4 หลายเดือนก่อน +1

    Go. Go. Go 🎉

  • @BishoySaeed-r2q
    @BishoySaeed-r2q 3 หลายเดือนก่อน +1

    i think there is a lag in the video ?

  • @pierre-louis2711
    @pierre-louis2711 4 หลายเดือนก่อน

    Hello and thank you as always for your awesome content. I juste miss one thing here : could you provide me some use-cases of creating component this way ? :)

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน

      There are many cases. For example, you might get a config from the server that describes which components should be created, and since you don't know the config at build time, you have no choice other than creating components at runtime.
      You also might track validity changes of your form and dynamically create/destroy components with error messages depending on the validity state of the form control.
      This is just the first that came to my mind :)

    • @pierre-louis2711
      @pierre-louis2711 4 หลายเดือนก่อน +1

      @@DecodedFrontend Thank you for your reply ! Creating component from a config file is a good example. Thank you ! It helps me.
      As concern as form errors messages, is that not the responsability of @if (*ngIf) ?

    • @Ahmed.Kharrat
      @Ahmed.Kharrat 4 หลายเดือนก่อน +1

      You can also create a modal service that creates and manages modal wrappers, allowing you to inject any component inside these wrappers, similar to how `NgbModal` works ;)

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน

      @@Ahmed.Kharrat dialog window a good example too. Thanks, Ahmed!

  • @BishoySaeed-r2q
    @BishoySaeed-r2q 3 หลายเดือนก่อน

    we need course for ssr or a video anything will be fine

  • @Ahmed.Kharrat
    @Ahmed.Kharrat 4 หลายเดือนก่อน

    Hi Dmytro, first of all thanks for the great content :)
    what you think about this alternative:
    this.#componentRef.instance.title.set('weather');
    and also we can guarantee type checking by
    (this.#componentRef.instance as WidgetComponent).title.set('weather');

  • @krishubisht
    @krishubisht 4 หลายเดือนก่อน +1

    Yo yo

  • @shubhamgoel7703
    @shubhamgoel7703 4 หลายเดือนก่อน +2

    Yo First comment :D

  • @Marshall86MT
    @Marshall86MT 3 หลายเดือนก่อน

    I found it a bit confusing, I'd rather have preferred having those solutions split instead of mixing them up in the same file. But thanks anyway 😊

  • @Edgars82
    @Edgars82 4 หลายเดือนก่อน +4

    In which case this can be useful? Just create component with all the inputs and outputs and render it based on condition.

    • @sokka7460
      @sokka7460 4 หลายเดือนก่อน +4

      For example, for a wyswyg, or if you have a dashboard where the user can create different type of widgets

    • @DecodedFrontend
      @DecodedFrontend  4 หลายเดือนก่อน +2

      It might be useful when you don't know in advance which component has to be rendered (e.g. It depends on configuration from server).
      Using if/else blocks might work ok if you have only 1-2 components to deal with, otherwise you will quickly notice that this solution doesn't scale well and each time you need to add a new component, you have to introduce another @if block.

    • @lucaspham5238
      @lucaspham5238 3 หลายเดือนก่อน

      I have a task to create a custom directive that takes either a class constructor, a `TemplateRef`, or a simple string as input, and displays it as an overlay when the user hovers over the element bound to the directive. Handling the `TemplateRef` and string can be done easily with `ngTemplateOutlet` and string interpolation, but rendering the class constructor requires extra steps like what we learn in this video

  • @diadetediotedio6918
    @diadetediotedio6918 2 หลายเดือนก่อน

    Angular has an absolutely terrible and boilerplaty way of doing things that in principle should not be that complex. But amazing video anyways!