How to unchecked and check the Nebular Check box dynamically after rendering - javascript

I am using a nebular theme checkbox in the Angular 8 App.
<nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)" >Enable </nb-checkbox>
i am updating the checkbox using "enable_checked" Boolean .When the component loaded it works fine but when I changed the value dynamically of BOOLEAN("enable_checked") it is not getting updated at the front end but the boolean is updated.

It's working you must change it like this :
<nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)" >Enable </nb-checkbox>
<button (click)="changeCheckbox()">Set false</button>
For more information: Docs
Typescript :
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
enable_checked = true;
changeCheckbox() {
this.enable_checked = false
}
}
Stackblitz Example: link

Related

Angular How to execute a function when a property changes in a component

Hi i am new to angular
this is my angular component
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
user = ""
constructor() { }
ngOnInit(): void {
}
}
Is there a way that I can execute a block of code whenever this user variable changes?
yes you can set condition on user or if the user is change from html then you can call that method on (change)="methodName()"

Angular change the state of a checkbox after user click

I have the following code that should set the checked value to false on click:
#Component({
template: `
<input type="checkbox" [checked]="checked" (change)="onChange()">
`
})
export class AppComponent {
checked = false;
onChange() {
setTimeout(() => {
this.checked = false;
}, 1000)
}
}
The problem is that if we click on the input and we wait for a second, it'll stay checked. Why is this happening? Why Angular doesn't change it to false again?
Long story short Angular checkboxes are just broken : Issue
If you however want to achive this effect i will recommend you to create your own custom component that will act the same way as a checkbox.
Here is one more fun example of Checkbox madnes try to interact with both "With track by" and "No track by" blocks and see what happens.
I think you can do that easily by using [(ngModel)]="checked". Your code is working in the stackblitz link. Please check that. Here is my code given below.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `
<input type="checkbox" [checked]="checked" [(ngModel)]="checked" (change)="onChange()" name="horns">
<label for="horns">Horns</label>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
checked = false;
onChange() {
setTimeout(() => {
this.checked = false;
}, 2000)
}
}
in angular you can manipulate dom using view child and element ref
first of all you need to import viewchild and elementRef in your component
app.component.ts
import { Component, VERSION } from "#angular/core";
import { ViewChild, ElementRef } from "#angular/core";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
#ViewChild("checkBox") el: ElementRef;
onChange() {
setTimeout(() => {
this.el.nativeElement.checked = false;
}, 100);
}
}
app.component.html
<input type="checkbox" #checkBox (click)="onChange()">
stackblitz

Why Angular 2+ innerHTML is calling method multiple times in a single statement, How to solve this

I have the template view like this.
<p [innerHTML]="myfunction()"></p>
and, ts file be like
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
myfunction(){
alert(name);
return '<div>abcd</div>';
}
}
Its a simple method calling from html to render the html content through innerhtml, here the myfunction() is calling multiple times, and i'm getting multiple alerts, can anyone help me to solve this.
the stackblitz for this is link
thanks in advance
You can use pure pipe to only rerun it if inputs to the pipe have changed:
#Pipe({name: 'functionCaller'})
export class FunctionCallerPipe {
transform(func: any, ...args: any[]): any {
return func(...args);
}
}
And use it like that:
<p [innerHTML]="myfunction| functionCaller : name"></p>
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
myfunction(name: string){
alert(name);
return '<div>' + name + '</div>';
}
}

String interpolation in Angular 2 not displaying updated value

I'm trying to learn Angular 2, and I'm running into a weird issue while following this documentation: https://angular.io/docs/ts/latest/guide/user-input.html for binding button clicks to a method on my controller.
I started off with their click event binding example. I created a simple app with the angular cli with ng new test-app and modified it so that it contains a single button that when I click, just adds a message to the page.
I have two components, the app component and the message components shown here:
message.component.html:
<p>{{message}}</p>
message.component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-message',
templateUrl: './message.component.html',
styleUrls: ['./message.component.css']
})
export class MessageComponent implements OnInit {
message: string;
constructor() {
this.message = 'some initial message';
}
ngOnInit() {
}
}
app.component.html:
<button (click)="addMessage()">Click</button>
<app-message *ngFor="let message of messages"></app-message>
app.component.ts:
import { Component } from '#angular/core';
import { MessageComponent } from './message/message.component';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
messages = [];
addMessage() {
const newMessage = new MessageComponent();
newMessage.message = 'Something else entirely';
this.messages.push(newMessage);
}
}
When I run this with ng serve, the button appears as expected, but when I click the button, only the message some initial message appears despite being given a different value by my app controller. While doing a search I found a different way to do the one-way databinding by replacing the string interpolation with: <p [innerText]="message"></p> but the result is the same.
I'm kinda at a loss here as to why it won't display the updated value of Something else entirely.
MessageComponent component should take message as #Input:
export class MessageComponent implements OnInit {
#Input() message: string;
}
AppComponent should send this input to its child like
<app-message *ngFor="let message of messages"
[message]="message.message"></app-message>

Angular 1 directive inside angular 2 application

We created an Angular 2 application using this awesome Angular2 Seed which works very well. So the question that I have is, how can I upgrade this Angular 1 directive:
import template from './sbgOutlineButton.html!text';
var app = angular.module('sbgOutlineButton', []);
app.directive('sbgOutlineButton', function() {
let link = function(scope, element, attributes) {
if (attributes.icon === undefined) {
let materialIcon = element.find('i.material-icons');
materialIcon.addClass('hidden');
}
};
return {
link: link,
restrict: 'E',
template: template,
replace: true,
transclude: true,
scope: { icon: '#' }
};
});
export default app;
So that I can use it in the following Angular 2 component:
import { Component, OnInit, ChangeDetectionStrategy } from '#angular/core';
import { UpgradeAdapter } from '#angular/upgrade';
#Component({
moduleId: module.id,
selector: 'test-page',
templateUrl: 'testpage.page.html',
styleUrls: ['testpage.page.css']
})
export class TestPage implements OnInit {
constructor() { }
ngOnInit() { }
}
Do you guys maybe have any idea on how I will be able to accomplish this? Is it even possible? Because a lot of the other articles that I have found during my research suggests that your "base" application should be Angular 1...
Thanks in advance.
Francois
How about converting your angular1 directive to angular2 directive?
NOTE: I don't know whether it will be useful or not but just have a look.
Look at the demo here : https://plnkr.co/edit/4Fhtm76iJl0aQmgjO7n0?p=preview
customeDirective.ts
import {Directive, Attribute,ElementRef,Renderer} from '#angular/core';
#Directive({
selector: '[myAttr]'
})
export class myDir {
constructor(#Attribute('icon') private icon,private el:ElementRef,private rd: Renderer){
console.log(this.icon);
if(this.icon===null){ //<--- you can play here as per your need.
console.log('icon is undefined');
}
else{
rd.setElementClass(el.nativeElement, 'myClass',true);
}
console.log(el.nativeElement);
}
}
AppComponent.ts
//our root app component
import {Component} from '#angular/core';
import {myDir} from 'src/customDirective';
#Component({
selector: 'my-app',
directives:[myDir],
template:
`
<style>
.myClass{
color:red;
background:yellow;
}
</style>
<div myAttr icon="myIcon">Angular2</div> <!-- icon attribute is present so it will add the class -->
<!-- OR USE BELOW HTML INSTEAD OF ABOVE -->
<div myAttr>Angular2</div> <!-- icon attribute is not present so it gives null -->
`
})
export class App {}
You need to upgrade to angular2 by using "#angular/upgrade": "2.0.0-rc.4",
Guide
Because a lot of the other articles that I have found during my
research suggests that your "base" application should be Angular 1...
It's if you have a already angular 1 project and you want to upgrade to one. Angular2 don't need angular1 as base
writing directive in angular2
import { Directive, ElementRef, Input } from '#angular/core';
#Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
My First Attribute Directive
Highlight me!
import { Component } from '#angular/core';
import { HighlightDirective } from './highlight.directive';
#Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
directives: [HighlightDirective]
})
export class AppComponent { }
you Don't need to mix up angular1 into two..

Categories

Resources