How to extend Angular Form Directive to have globally autocomplete="off" - html

As we know in Angular <form> is a directive. I'm wondering if there is any way to extend that directive.
I need this because I want to append attribute autocomplete="off" always when I use <form> on my view. Or maybe there is another, easier way to set it globally?

Angular diretive selector can also be select by css.As #Andrei Gatej mentioned in the comment you can use hostbinding to bind autocomplete attribute to all input inside form like this:
import { Directive, HostBinding } from '#angular/core';
#Directive({
selector: 'input[type="text"]'
})
export class FormDirective {
#HostBinding('attr.autocomplete') autoComplete ='off';
constructor() {
}
}

you should write own directive. Here is docs https://angular.io/guide/attribute-directives

Related

How to pass Angular directive by reference?

In an existing component template I have this (simplified) element:
<input type="button" #refreshPrice />
This is picked up (I don't know the correct term) by this property so we can subscribe to it's click event and call a function when the input element is clicked.
I want to replace this input element with a component I've developed, which would make it look (simplified) like this:
<spinner-button #refreshPrice></spinner-button>
This child component has this as its (simplified) template:
<button>
<mat-spinner></mat-spinner>
</button>
So now the button element, in the child component template, needs to have the #refreshPrice hash attribute (?) attached.
To do this, perhaps the spinner-button element should take the name of the hash attribute as an attribute value. Here is the complete spinner component class file:
import { Component, Input, OnInit } from "#angular/core";
#Component({
selector: "spinner-button",
templateUrl: "./spinner-button.component.html",
styleUrls: ["./spinner-button.component.css"]
})
export class SpinnerButtonComponent implements OnInit {
constructor() {}
#Input() targetElement: string;
ngOnInit() {
}
}
In theory, the targetElement property can then be attached to the button element as a hash attribute - but how is this done?
the #Input() attribute here allows you to bind a value to a variable on your component, if you want to have the parent do something based on your components data, you might want to use #Output() and emit a custom event. If the requirement is just listen to a click event then adding a (click)=functionToBeCalled() should help your cause here.
You can refer to the official docs as well:
https://angular.io/guide/inputs-outputs

Angular 8 | Hide element using Directive

I want to hide specific element using Directive in Angular 8 when user click on input field.
Code is as per below
HTML
<input [choosecountry] type="text" />
directive.ts
#Directive({
selector: '[choosecountry]'
})
export class ChoosecountryDirective {
constructor( ) { }
}
Angular already have ngIf to accomblish this piece of requirement.
You can use [hidden]="true" this element will created on DOM as hidden, which is opposite to ngIf
yes, using Directive you can hide or show element.here is an example

Inner HTML of ng-container, Angular 4?

I want to dynamically place an html code in my html code, So I write the following code:
<ng-container [innerHTML]="buttonIcon"></ng-container>
Angular says innerHTML is not valid attribute for ng-container
I don't want to use third html tag like follows:
<div [innerHTML]="buttonIcon"></div>
So how can I insert html codes without any tag inner html binding?
[outerHTML]
will do the trick to replace the outer element.
In your case
<div [outerHTML]="buttonIcon"></div>
It's true, that it's important to have a clean HTML structure for e.g. keeping CSS rules as simple as possible.
You can use ngTemplate:
<ng-template #buttonIcon>
<div> Your html</div>
</ng-template>
<ng-container
*ngTemplateOutlet="buttonIcon">
</ng-container>
** Please read the comments. This answer might be wrong. I dont know, have not looked into it again **
ng-container does not get rendered to html, it is a mere structural directive.
The Angular is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
So there is no element to put html into. You need to work with a sub-div. If there is no need for a sub-div in your opinion, then you could most probably also just replace ng-container with div itself and not use the container at all.
If for any reason you need to replace the DOM element you can use a div with an id and then use the #ViewChild decorator and ElementRef to get access to the nativeElement from the controller and set the outerHtml property.
app.component.tml
<div #iconButton></div>
app.component.ts
import { Component, ViewChild, ElementRef, ViewEncapsulation, AfterViewInit }from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
encapsulation: ViewEncapsulation.None
})
export class AppComponent implements AfterViewInit{
#ViewChild('iconButton')
iconButton: ElementRef;
ngAfterViewInit(){
this.iconButton.nativeElement.outerHTML = '<button>My button</button>'
}
}
We need to use none as encapsulation policy because our template only includes the div to be replaced.
Stackblitz example: https://stackblitz.com/edit/angular-fa1zwp

Angular2 Declaring a directive's selector to require a text input

I have just created a number directive :
#Directive({
selector: '[ngModel][number]'
})
export class NumberDirective {...}
I would like my selector to be even more specific and requires a text input :
<input type="text" [(ngModel)]="..." [number]="...">
You can use attribute selectors with value
selector: 'input[type="text"][ngModel][number]'
See also https://developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors

Styled HTML content dynamically switched with tabs using Angular 2

I am attempting to create a reusable angular2 component that accepts an array of URLs to html files on my server and creates a content window with tabs to switch between "chapters", effectively swapping out the html and css inside the content window. I have tried all sorts of things including iframes but those don't work, the angular 1 ng-include work-arounds that I can find on StackOverflow but they have all since been deprecated, and the closest I've got is building a component that you can #Input html and it interpolates the content but style won't apply and angular strips out any style or script tags. Here is what I have tried.
In my parent component class:
htmlInput: string = "<h1>Why Does Angular make this so hard?</h1>";
cssInput: string = "h1 { color:red; }"
Parent Component HTML:
<app-html [html]='htmlInput' [css]='cssInput'></app-html>
My HTML Component:
import { Component, Input, OnInit } from '#angular/core';
#Component({
selector: 'app-html',
template: '<div [innerHtml]=html></div>', //This works but no style
//template: '{{html}}', //This displays the actual markup on page
styles: ['{{css}}'] //This does nothing
//styles: ['h1 { color: red; }']//Also nothing
})
export class HtmlComponent implements OnInit {
#Input() html: string = "";
#Input() css: string = "";
ngOnInit() {
}
}
The result of this code is
Why Does Angular make this so hard?
But no red color. Maybe style is applied before the innerHtml is added to DOM? I don't know but just putting {{html}} results in displaying the actual markup with the h1 tags visible.
The reason I want to do it this way is that I have a bunch of HTML pages already created sitting in a folder on my server from before I angularized my site that all share a single style sheet. I'd like to just be able to flip through them like pages in a book without reloading the page and since there are so many and I'm likely to add more all the time, I'd really rather not create routing for every single one. (I already have routing for basic site navigation.)
Does anybody have a better suggestion for how to embed styled HTML into a page dynamically in the most recent version of Angular 2? At the time of this post we are in 2.0.0-beta.17.
OR... I already figured I may be approaching this issue from the entirely wrong angle. There must be a reason Angular is making this so difficult and deprecating all the solutions people have come up with so If anyone has a suggestion about how I could achieve the same results in a more angular friendly way I'd love to hear that too.
Thank you.
Edit:
I was able to fix my issue by creating a pipe which sanatizes the html before adding it to an iframe.
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url: string) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
And then you can just pass your html into the iframe.
<iframe width="100%" height="1000" frameBorder="0" [src]="url | safe"></iframe>
This is useful to me since I have some old pages that use all sorts of jquery and style etc. This works as a quick fix to have them show up.
Angular2 rewrites the styles added to a component by including the dynamically added attributes like _ngcontent-yle-18 into the CSS selectors.
Angular2 uses this to emulate shadow DOM style encapsulation. These attributes are not added to dynamically added HTML (for example with innerHTML).
Workarounds
add styles to index.html because these styles are not rewritten by Angular2
set ViewEncapsulation.None because then Angular doesn't add the encapsulation emulation attributes
use /deep/ to make Angular2 ignore the encapsulation emulation attributes
See also Angular 2 - innerHTML styling
You should wrap your css into an object and use ngStyle to bind it to your component rather than the styles attribute, because styles does not support data binding.
Example:
htmlInput: string = "<h1>Why Does Angular make this so hard?</h1>";
cssInput: string = "{h1 { color:red; }}"
Parent Component HTML:
<app-html [html]='htmlInput' [css]='cssInput'></app-html>
Your HTML Component:
import { Component, Input, OnInit } from '#angular/core';
#Component({
selector: 'app-html',
template: '<div [innerHtml]="html" [ngStyle]="css"></div>',
styles: []
})
export class HtmlComponent implements OnInit {
#Input() html: string = "";
#Input() css: string = "";
ngOnInit() {
}
}