Create reusable block of vue template within creating new component - html

In some instances, I need to just repeat some html code within my Template to DRY it up, but making a new component and passing a ton of props and dynamic data to it seems like overkill. Is there a way to define a repeatable block of template code that can just be reused?
A good example of this is my vuelidate validation error messages that are repeated. I don't want to create an entire vue component for them because then I need to pass in the validation, validation prop and a few other things so that seems like creating more complexity just to DRY up a little bit of the template.
I have this block of code on three different scenarious in the same template, is there a way I can just define them as a block to reuse. Literally nothing changes so it's very much against DRY principles.
<span
v-if="!$v.initialReplyText.required"
class="error">Your reply cannot be empty.</span>
<span
v-if="!$v.initialReplyText.maxLength"
class="error">Your reply cannot be over 2,000 characters.</span>

you can do dynamic binding using v-bind, that way you don't need to bind all properties individually.
<!-- pass down parent props in common with a child component -->
<child-component v-bind="$props"></child-component>
src: https://v2.vuejs.org/v2/api/#v-bind
You can also use slots, or scoped slots, which are commonly used for things like wrapping error messages in more complex markup.

If all elements are consecutively arranged as in your example, you can use v-for as below:
<span v-for="(criteria, msg) in {'Your reply cannot be empty.': !$v.initialReplyText.required, 'Your reply cannot be over 2,000 characters.': !$v.initialReplyText.maxLength }"
v-if="criteria" class="error">
{{msg}}
</span>

Related

How to get a I18n variable value I can return to my Angular parent component?

I'm new to Angular and I just put in place an i18n (2 languages) system for a website I am creating. Everything works properly but in order to switch from one language to another in my header, I feel stuck.
I followed the Angular documentation to transfer my variables from child to parent component and I ended with this:
<input type="text" id="item-input" #lang>
<button type="button" (click)="changeChosenLang(lang.value)">
{{ 'global.lang' | translate }}
</button>
As you can see, I write my language in the input form and I send it to the proper component with a button. What I wanted was to click on my 'global.lang' text and to be able to send its value to the parent component, since the value is the language which is not actually used.
I don't know how to put my 'global.lang' text in a variable, neither what kind of balise I can use. Also I didn't know how to summarize my problem to search for it on StackOverflow so if you know a similar post, don't hesitate to post the link.
Thank you for your reading!
I found a less tortured way (poor brain) to have the result I wanted:
<span (click)="changeChosenLang()">
{{ 'global.lang' | translate }}
</span>
First I temporary changed my button to a span balise and I deleted the parameter from my changeChosenLang() function. Then, I transferred a variable 'lang' from my parent component to this one, witch contains the value of the language chosen in my app constructor. At each click, I change its value in my changeChosenLang() function and everything works great!
I hope it can help someone someday. The moral of this post is: the simpler, the better! Have a good day.

Pairing or Connecting input and button elements with angular

I was following the tutorial Tour of Heroes. While adding a new hero they say
You can use an element paired with an add button.
Insert the following into the HeroesComponent template, after the heading:
<div>
<label for="new-hero">Hero name: </label>
<input id="new-hero" #heroName />
<!-- (click) passes input value to add() and then clears the input -->
<button type="button" class="add-button" (click)="add(heroName.value); heroName.value=''">
Add hero
</button>
</div>
Here I don't understand what is #heroName inside in input element (what is it called) and how does it help in pairing that input element with the button element.
Basically, what is that #<keyword> syntax within that input element. I know that it is not the id as that is already declared.
To answer the question, it's a reference to the input. You can find more details here:
https://angular.io/guide/template-reference-variables
Template variables help you use data from one part of a template in
another part of the template. Use template variables to perform tasks
such as respond to user input or finely tune your application's forms.
In the tutorial context, it's a reference to the input element. It helps to pair it with a button to be able to access it's value, without having to actually define a variable in the component.ts and trying to update the template directly. This help you "skip" a step, and actually have direct access to that value.
Template reference variables can become very handy in certain cases and are commonly used for example in angular material ( to call a function for a component )
<mat-menu #menuComponent ...></mat-menu>
<button (click)="menuComponent.close()"></button>
In the above example, you bind the menuComponent variable to "mat-menu" component, in which case you can access all the variables, public methods of such. In that case we can call "close" method from the mat-menu component.
Let me know if this is still unclear and I can try to give you more examples and explanation

Minimal example to wrap a library component in angular12

In developing an Angular app, I find myself using similar HTML components with the same arugments over and over. For example:
<fa-icon class="tms-hover-animation px-2" (click)="onDeleteContact(row)"
[icon]="faTrash" ngbTooltip="Delete Contact" placement="bottom auto" container="body">
The placement and container fields are redundantly defined over and over and over. What I'd much rather be able to do is the following:
<my-fa-icon (click)="onDeleteContact(row)" [icon]="faTrash"></my-fa-icon>
However,I can't find an minimal example of how to do this.
To clarify: my main misunderstanding is how can I reuse <fa-icon and pass all of its inputs (click, icon, etc... ) without having to explicitly redeclare them in my wrapper? Something like:
#Component
FaIconWrapper
args: <-- These automatically passed into underlying fa-icon
How could we create a custom HTML element like this with default arguments, but still pass (click), [icon] and any other inputs down into the wrapped component?
I'm also worried about falling into an anti-pattern here.

Angular4 ng-content gets built when ngIf is false

I have a problem with the new ng-content transclusion.
Let's say I have a component my-component that, in its ngOnInit() function does some heavy operation on load (for now, just a console.log()).
I have a wrapper, that displays the content via transclusion (my-wrapper.component.html).
<ng-content></ng-content>
If I set the surroundings up like this, the log statement doesn't show:
<my-wrapper *ngIf="false">
<my-component></my-component>
</my-wrapper>
I assume, the my-wrapper component does not get built, so the content is ignored.
But if I try to move the logic into the my-wrapper component like this (my-wrapper.component.html):
<ng-container *ngIf="false">
<ng-content></ng-content>
</ng-container>
I always see the console.log() output. I guess, the my-component gets built and then stored away until the *ngIf becomes true inside my-wrapper.
The intention was to build a generic "list-item + detail" component. Say I have a list of N overview-elements (my-wrapper), that get rendered in a *ngFor loop. Every of those elements has its own detail component (my-component) that is supposed to load its own data, once I decide to show more infos to a specific item.
overview.html:
<ng-container *ngFor="let item of items">
<my-wrapper>
<my-component id="item.id"></my-component>
</my-wrapper>
</ng-container>
my-wrapper.component.html:
<div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail">
<ng-content></ng-content>
</div>
Is there a way to tell Angular, to ignore the transcluded content until it is necessary to be added to the page? Analogously to how it was in AngularJS.
Based on the comment of #nsinreal I found an answer. I find it to be a bit abstruse, so I'm trying to post it here:
The answer is to work with ng-template and *ngTemplateOutlet.
In the my-wrapper component, set up the template like this (my-wrapper.component.html):
<div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail" [hidden]="!isInitialized">
<ng-container *ngTemplateOutlet="detailRef"></ng-container>
</div>
Note, that the [hidden] there is not really necessary, it hides the "raw" template of the child until it decides it is done loading. Just make sure, not to put it in a *ngIf, otherwise the *ngTemplateOutlet will never get triggered, leading to nothing happening at all.
To set the detailRef, put this in the component code (my-wrapper.component.ts):
import { ContentChild, TemplateRef } from '#angular/core';
#Component({ ... })
export class MyWrapperComponent {
#ContentChild(TemplateRef) detailRef;
...
}
Now, you can use the wrapper like this:
<my-wrapper>
<ng-template>
<my-component></my-component>
</ng-template>
</my-wrapper>
I am not sure, why it needs such complicated "workarounds", when it used to be so easy to do this in AngularJS.
By doing this:
<my-wrapper *ngIf="false">
<my-component></my-component>
</my-wrapper>
You are not calling MyComponent component, because the *ngIf is false. that means, that not calling it you are not instancing it and, therefore, not passing through its ngOnInit. And that's why you are not getting the console log.
By doing this:
<ng-container *ngIf="false">
<ng-content></ng-content>
</ng-container>
You are inside the component, you are just limiting what to render in your template, but you already instanced your component and, therefore, you passed through your ngOnInit and you get your console log done.
If, you want to limit something (component call with selector or a ng-content or even a div) until you have some data available, you can do the following:
datasLoaded: Promise<boolean>;
this.getData().subscribe(
(data) => {
this.datasLoaded = Promise.resolve(true); // Setting the Promise as resolved after I have the needed data
}
);
And in your template:
<ng-container *ngIf="datasLoaded | async">
// stuff here
</ng-container>
Or:
<my-component *ngIf="datasLoaded | async">
// Didn't test this one, but should follow the same logic. If it doesn't, wrap it and add the ngIf to the wrapper
</my-component>
It’s because Ng content happens at the build time and when you pass the content it is actually not removed or recreated with the ngIf directive. It is only moved and the component is instantiated .
I encountered this problem recently as well but settled on a different solution than the currently accepted one.
Solution (TL;DR)
(Solution is for AngularDart; I figure it's similar in Angular though)
Use a structural directive; tutorials linked below.
Instead of:
<my-wrapper>
<my-contents></my-contents>
</my-wrapper>
your usage becomes:
<div *myWrapper>
<my-contents></my-contents>
</div>
which is shorthand for the following (in AngularDart; I think Angular uses <ng-template>)
<template myWrapper>
<div>
<my-contents></my-contents>
</div>
</template>
The MyWrapper directive logic is similar to NgIf except it has its own logic to compute the condition. Both of the following tutorials explain how to create an NgIf-like directive and how to pass it your own inputs using the special microsyntax (e.g. *myWrapper="myInput: expression"). Note that the microsyntax doesn't support outputs (#Output), but you can mimic an output by using an input that is a function.
Tutorial for Angular
Tutorial for AngularDart
Caveat: Since this is just a directive, it shouldn't do anything more complicated than instantiating a template ref at the appropriate time and maybe specifying some DI providers. For example, I would avoid trying to apply styles or instantiating a complex tree of components in the directive. If I wanted to create a list component, I would probably take the #ContentChild(TemplateRef) approach described in another answer; you would lose the asterisk shorthand for creating <template> but you would gain the full power of components.
My problem
My team owns an app that's part of a larger web application with other apps owned by other teams. Our components assume they can inject a MyAppConfiguration object, but this object can only be injected after it is loaded with an asynchronous request. In our app this is not a problem: we have a "shell" component that hides everything behind an ngIf until the configuration is loaded.
The problem is when other teams want to reference our components. We don't want them to duplicate the "wait until configuration is loaded" logic every time, so I tried creating a wrapper component that can be used like so:
<my-app-wrapper>
<my-app-component></my-app-component>
</my-app-wrapper>
The wrapper injects a service object and hides its contents behind an ngIf until the service says that the configuration is loaded.
Like the question poster, I discovered that the ng-content approach doesn't work as intended: while the contents are correctly hidden from the DOM, Angular still instantiates the components causing dependency injection to fail.
The solution that I settled on was to rewrite the wrapper component as a structural directive.

Component selector in variable - Angular 2

I have written my own table module. Calling it in HTML code looks like this:
<my-table [data]="variableWithArr"></my-table>
Now, pretty nice table is being displayed. Cool. But what if I want to have a progress bar in some column of table? I thought that I could put a HTML code with component selector as value, for example bootstrap progressBar, like this:
for(let record of variableWithArr) {
record[0] = '<ngb-progressbar type="danger" [value]="100"></ngb-progressbar>';
}
Unfortunatelly, Angular displays only a HTML code but dooes not interpret it as component selector, so I receive something like that in DOM:
<td><ngb-progressbar type="danger" [value]="100"></ngb-progressbar></td>
How to fix it?
This is not how Angular works - you can't insert arbitrary HTML (innerHTML or otherwise) and expect that directives will be picked up & applied. Making Angular work this way would require shipping entire compiler to a browser and would defeat the whole purpose of all the great optimizations that can be done with the ahead-of-time (AOT) compilation.
tl;dr; nope, you can't do this and this has nothing to do with the ng-bootstrap project, but rather with design decisions behind Angular.
By looking at the docs you need to use the property [innerHTML], but to be clear only use it when you trust the code!!
So should be something like this:
<td [innerHTML]="record"></td>