I am creating a button and assigning class in component.ts. Style of css does not apply on the button (button font color doest not change). Code of component.ts is
let button = document.createElement('button');
button.innerHTML = 'North';
button.setAttribute('class', 'btn');
let element = document.createElement('div');
element.appendChild(button);
and component.css is
.btn
{
color: red;
}
please try this
button.classList.add("btn");
Use angular components for create buttons
#Component({
selector: 'my-app',
templateUrl: '',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
#ViewChild('element', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(
private _componentFactoryResolver: ComponentFactoryResolver,
private _injector: Injector,
) {}
addButton(): void {
const [componentRef, componentInstance] = this._createButton();
componentInstance.title = 'North'
componentInstance.class = 'active'
this.container.insert(componentRef.hostView);
}
private _createButton(): [ComponentRef<ButtonComponent>, ButtonComponent] {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(ButtonComponent);
const componentRef = componentFactory.create(this._injector)
const componentInstance = componentRef.instance;
return [componentRef ,componentInstance];
}
}
button component
#Component({
selector: 'app-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.css'],
})
export class ButtonComponent {
#Input() title: string;
#Input() class: string = '';
}
I put the whole example on stackblitz
Related
I'm using canvas and I think the default width, and height size 300px/150px. I want to customize the width, I use Angular.
I did try to put canvas { width:400px } in app.component.css but didn't work
app.component.ts
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = '30px Arial';
context.fillText('Hello World', 10, 50);
This is my one example for canvas in Angular-13
app.component.ts File
import { Component, ViewChild, ElementRef, AfterViewInit } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements AfterViewInit {
context: any;
#ViewChild('myCanvas')
private myCanvas: ElementRef = {} as ElementRef;
ngAfterViewInit(): void {
this.context = this.myCanvas.nativeElement.getContext('2d');
if(this.context) {
this.myCanvas.nativeElement.width = 400;
this.context.font = '30px Arial';
this.context.fillText('Hello World', 10, 50);
}
}
}
app.component.html File: I have added my canvas in template file like below.
<canvas #myCanvas>
Hope this help. Thanks!
In my SPA build in Angular i want to add a class to the navigation every time the user arrives to a certain section. I have been trying the following solution as seen in this stackblitz.
https://stackblitz.com/edit/angular-ivy-gdxcw8?file=src/app/app.component.ts
You need to query the HTML elements in ngOnInit.
Add this:
ngOnInit() {
this.sections = document.querySelectorAll('section');
this.navLi = document.querySelectorAll('nav .container ul li');
}
After changing your code to:
import { Component, HostListener, VERSION } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
sections: NodeListOf<HTMLElement>;
navLi: NodeListOf<HTMLElement>;
ngOnInit() {
this.sections = document.querySelectorAll('section');
this.navLi = document.querySelectorAll('nav .container ul li');
}
#HostListener('window:scroll', ['$event'])
onscroll() {
var current: any = '';
this.sections.forEach((section) => {
const sectionTop = section.offsetTop;
if (scrollY >= sectionTop - 60) {
current = section.getAttribute('id');
}
});
this.navLi.forEach((li) => {
li.classList.remove('active');
if (li.classList.contains(current)) {
li.classList.add('active');
}
});
}
}
I get your desired behaviour.
Read more about ngOnInit at https://angular.io/guide/lifecycle-hooks
I am trying to display full-calendar module in ngx bootstrap tab teg but at the beginning I am getting only header after clicking header buttons it is displaying all calendar
I have tried to move assignment in ngOnInit but it didn't work
import {AfterViewInit, Component, OnInit} from '#angular/core';
import dayGridPlugin from "#fullcalendar/daygrid";
#Component({
selector: 'app-calendar-module',
templateUrl: './calendar-module.component.html',
styleUrls: ['./calendar-module.component.scss']
})
export class CalendarModuleComponent implements OnInit, AfterViewInit {
public calendarPlugins = [dayGridPlugin];
constructor() { }
ngOnInit() {
}
ngAfterViewInit(){
}
}
<full-calendar
defaultView="dayGridMonth"
[plugins]="calendarPlugins"
[weekends]="false"
[events]="[
{ title: 'event 1', start:'2019-08-19', end:'2019-08-30', color:'red' }
]"
></full-calendar>
Link to screenshot
this worked
ngOnInit() {
setTimeout(() => {
this.calendarComponent.getApi().render();
}, 300);
}
I want to assign css class based on some calculation. This is my component class:
#Component({
selector: 'app-render-json',
template: `<div [innerHtml]="html | safeHtml"></div>`,
styleUrls: ['./render-json.component.css'] , encapsulation: ViewEncapsulation.ShadowDom
})
export class RenderJsonComponent {
#Input() myJson: any;
html = ``;
static levelDeep = 1
ngOnInit() {
this.renderJson(this.myJson)
}
renderJson(obj) {
RenderJsonComponent.levelDeep = RenderJsonComponent.levelDeep + 1
for(var key in obj) {
if(key != 'id') {
this.html = this.html + `<div class="col-md-${RenderJsonComponent.levelDeep} col-md-offset-${RenderJsonComponent.levelDeep}">${obj[key]}</div>`
// This does not work but I want to do something like this
}
}
}
}
Basically, I need to render some JSON in a GRID style through bootstrap using offset classes but this does not work somehow. Any help is appreciated.
#Component({
selector: 'app-render-json',
template: `<div [innerHtml]="safeHtml"></div><div *ngFor="jsonElements as element" class="element.class">element.obj</div>`,
styleUrls: ['./render-json.component.css'] , encapsulation: ViewEncapsulation.ShadowDom
})
export class RenderJsonComponent {
#Input() myJson: any;
myLevelDeep = 1;
jsonElements = [];
ngOnInit() {
this.renderJson(this.myJson)
}
renderJson(obj) {
this.myLevelDeep = RenderJsonComponent.levelDeep + 1
for(var key in obj) {
if(key != 'id') {
jsonElements.push({class:"col-md-" + this.myLevelDeep + " col-md-offset-" + this.myLevelDeep, obj: obj[key]});
}
}
}
}
I have an angular2 app with an RC5 style submodule. The module is my tutorial module, with tutorial.component as it's root component.
#Component({
selector: 'tutorial',
template: `
<div class="content row">
<div class="col s9">
<h1>Tutorial</h1>
<router-outlet></router-outlet>
</div>
</div>`,
styleUrls: ['./app/tutorial/tutorial.css'],
directives: [ROUTER_DIRECTIVES],
encapsulation: ViewEncapsulation.None
})
export class tutorialComponent {
public chapters = _chapters;
clickedItem: number = 0;
}
Here you can see the module routes:
const tutorialRoutes: Routes = [
{
path: 'tutorial',
component: tutorialComponent,
children: [
{ path: 'chapter/:id', component: chapterComponent },
{ path: '', redirectTo: 'chapter/0', pathMatch: 'full'},
]
}
];
So that's fine, however, in my child Component, chapterComponent, my css isn't being applied. Here is the component:
#Component({
selector: 'chapter',
template: `<div [innerHTML]="content"></div>`,
styleUrls: ['./app/tutorial/chapter/chapter.css']
})
export class chapterComponent implements OnInit, OnDestroy {
private sub: Subscription;
private content: string = '';
constructor( private route: ActivatedRoute) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
var id: string = params['id'];
this.content = id;
var that = this;
var _url = './chapter/' + params['id'] + '.html';
$.ajax({
url: _url,
success: function (result) {
that.content = result;
}
});
});
}
}
But if I use the exact same path to the chapter.css file in my tutorial component, then the styles are applied.
Why are my child components behaving differently to parent components with respect to css application.