ngIf and click not working for dynamic html in angular2 - javascript

ngIf and click not working for dynamic html.
when load html using innerHtml then ngIf and click event not loading.
export class FillInBlanksComponent implements OnDestroy, OnInit {
question = '';
editable = true;
ngOnInit() {
question = '<span *ngIf="editable" name="answers['+incr+']" contenteditable="true" (click)="onclick()"> </span>';
}
onClick(){
alert("clicked!!!!");
}
}

The function you're calling is (click)="onclick()" but you've defined onClick().
Another thing is, you might want to DOM Sanitize the string else you'll get a warning. Please check this answer out on how to do that.

check you have done spelling mistake use (click)="onClick()"
you are using small c in your function call

Related

Conditinally rendering text using Angular clipboard

I want to implement a simple copy-to-clipboard function in my Angular application.
The function to copy works, however, I do not understand how conditional statements in Angular as most of my experience is in React.
In React I would define my variable
[copy, setCopy] = useState(false)
Then, I would pass this into wherever I want to change the text or graphic element:
<button>{copy ? "click to copy" : "url copied"}</button>
Using the Angular docs, this is what my copy function looks like in Angular:
export class ThankyouComponent {
copied = false
value ='https://url.com'
}
And here is where I want to use it in my HTML file
<button [cdkCopyToClipboard]="value">{{SOME_EVENT ? "copy url" : "url copied" }}</button>
How do I access the click event of cdkCopyToClipboard in order to conditionally render the string within the button as in my React example? I've been looking around online and can't find a solution.
to display something conditionally inside an HTML template in Angular, you can use property that holds text
In HTML button attribute you can add
(click)="myOnClickMethod()"
Which calls method inside ts file whenever click event occures.
And in that method (that should belong to ts file in the same component you can do something like which changes button text to anything you want after the click.
#Component({
// Omitted for simplicity
})
export class MyComponent{
public buttonText: string = 'Copy url'
public myOnClickMethod(): void {
this.buttonText = 'Copied'
}
}
Then you can pass that variable with string interpolation to that button content like
<button ...>{{ buttonText }}</button>
Bonus
If you want to display some blocks conditionally, like some kind of fallback in case of no data, for example, in React you would probably do something like
if(!props.myList || props.myList.length < 1) return <strong>No data</strong>
return <> // some processing </>
In Angular you can use *ngIf directive
<div *ngIf="myList?.length > 0 else no-data">
// some processing
</div>
<ng-template #no-data>
<strong>No data</strong>
</ng-template>
Of course you donĀ“t need to use else statement and you can use opposite condition in other *ngIf instead.

(Angular) How can I get the #tag definition in html to Javascript?

I am having difficulty working on an Angular project.
In HTML...
<input #abc>...</input>
In Javascript
let var = ... *(how can i get the input element 'abc' to javascript?)*
I know it's too basic,
I am having a lot of trouble. Help!
this a template reference, you need to grab this element using #ViewChild decorator
#Component({
template:" <input #abc>...</input> "
})
export class SomeComponent implements AfterViewInin{
#ViewChild("abc")
element:ElementRef<HtmlElement>;
ngAfterViewInit(){
console.log(this.element.nativeElement);
}
}
I encourage you to read, the following topics to get the knowledge for that
https://angular.io/guide/component-interaction#parent-calls-an-viewchild for viewChild
https://angular.io/guide/template-syntax#template-syntax for template reference
you can refererence it with a
#VhiewChild('abc') myInput: ElementRef;.
however if you want JUST value more valid and easy way to make a field on you class, lets say value
and update it when your input updates <input (input)="value = $event.target.value" [value]="value">
if you use event
<input #abc (click)="getabc(abc)">...</input>
getabc(element) { console.log(abc) } //element input
if just get in .ts
#ViewChild("abc") element:ElementRef<HtmlElement>;
you can get element .

Angular 2+ using jQuery's append alternative in app.component.ts method

I am using angular 7 and I have a textarea on my app.component.html file.
I have given it an id to ta.
On my app.component.ts I have a method and I want to append a string into my textarea.
So I have this:
// app.component.html
<textarea id="ta"></textarea>
// app.component.ts
mymethod() {
// $('#ta').append("this text was appended");
// But I need to do the above without jQuery
}
How can I do this?
You are thinking in jQuery, while you should think in angular. Think of the textarea as a variable. When someone updates the textarea, the variable updates as well, and backwards - if the variable updates, the textarea too.
You can use ngModel to bind a variable to an input or a textarea. Then, append the string to the variable, and it will update the textarea.
// app.component.html
<textarea id="ta" [(ngModel)]="textareaValue"></textarea>
// app.component.ts
public textareaValue: string;
mymethod() {
this.textareaValue = "this text was appended";
}
Don't forget to include the FormsModule in the app module (here you can see how)

during the initial page load need to change the add/edit color

I am learning angular2.
during the initial page loads, I need to change the add/edit preference colour.
can you tell me how to fix it?
I googled for the load event.
but I am not able to find out anything.
providing my code below.
https://stackblitz.com/edit/angular-zddcxy?file=app/app.component.html
<!-- language-all: lang-or-tag-here -->
public loadColor() {
console.log('this.changeColor--->');
}
<span id="open1" (click)="loadColor()">add/edit prefrence</span>
Use ngOnInit and ViewChild decorator
#ViewChild('open1') el:ElementRef;
ngOnInit(): void {
const span = this.el.nativeElement;
span.style.color = 'red';
}
And in HTML add #open1 as ref
<span #open1 id="open1" (click)="loadColor()">add/edit prefrence</span>
see https://stackblitz.com/edit/angular-uvmusm?file=app/app.component.html
For catch initial page loads event, you need to use Angular component lifecycle hook. So you need it add ngOnInit is called by Angular completed creating the component.
For add ngOnInit you need import OnInit
import {Component, OnInit} from '#angular/core';
You need to add ngOnInit hook method
//implement OnInit's `ngOnInit` method
ngOnInit(){
console.log('this.changeColor--->');
}
For more information https://angular.io/guide/lifecycle-hooks
I have updated your code https://stackblitz.com/edit/angular-gzqebz?file=app/app.component.ts

Weird behaviour querySelector

I have component in angular
in component.ts i have line of code that serach html element
var myArticle = document.querySelector('article');
this return null
in component.html
<article id="bodyArticle" *ngIf="isClicked"></article>
but when I use article in sibling component.ts
var myArticle != null from component.ts
How it's work querySelector serach element in all file project ?
I also have other problem. In same componen.html i have button
<div class="btnGrp">
<button (click)="loadXML($event)">Load</button>
<input type="file" name="img" multiple (change)="onChange($event)">
</div>
<article id="bodyArticle" *ngIf="isClicked"></article>
When i click button one click emitted is value true firstly and i must click second to button to load thata to article content
snippet from component.ts
loadXML(event?: Event) {
var myArticle = document.querySelector('article');
console.log(myArticle);
if(this.imageService.getBodyRes() == ''){
myArticle.textContent = 'Error can't load data';
this.isClicked = true;
this.xmlLoadedEvent.emit(this.isClicked);
} else {
myArticle.textContent = this.imageService.getBodyRes();
console.log(myArticle.textContent);
this.isClicked = true;
this.xmlLoadedEvent.emit(this.isClicked);
}
}
How to do that when i click button in article tag ngIf set true value and also loadData without dobule click.
Try to avoid using the document object and its methods in Angular. It will make your life very difficult if you try to do that.
<article #articleId id="bodyArticle" *ngIf="isClicked"></article>
You can put a template variable name on the article tag, and then query it with angular's 'ViewChild' class like so -
import { Component, ViewChild, ElementRef, ...others?....} from '#angular/core'
export class MyComponent {
articleToggle: boolean = false; // add a toggle in your component for turning the article on
#ViewChild('articleId') article: ElementRef;
ngAfterViewInit() {
this.article.nativeElement.<<access DOM attributes here>>
}
}
This will give you access to the DOM node, like you expected your document query to have done, but even so, there are probably still better ways to do what you are doing, especially since you mentioned you are trying to use the article in sibling components. If that is the case, you may want to make it its own component allowing you to avoid queries altogether, but again, impossible to know with so little info.
Also, its generally recommended to avoid comparing to null entirely in typescript. Use 'undefined' instead.
<button (click)="loadXML($event); articleToggle = true">Load</button>
Set your variable to true on click, and then for the article.
<article #articleId id="bodyArticle" *ngIf="articleToggle"></article>
Now it will appear after the first click of the button, as that will be the only time the value changes from false -> true.

Categories

Resources