Change default width and height Canvas size in Angular - css

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!

Related

Adding class by scrolling to certain sections angular

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

Give class to dynamically created button in angular

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

Full Calendar's body is not displayed on load

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);
}

Using CSS hover property in Angular directive?

Here is the directive, the default one.
import { Directive, Input, Renderer2, ElementRef } from '#angular/core';
#Directive({
selector: '[newBox]'
})
export class BoxDirective {
#Input() backgroundColor = '#fff';
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit(): void {
this.renderer.setStyle(this.el.nativeElement, 'background-color', this.backgroundColor);
}
}
Now, on hover, I want the background-color to change. How do I do that in the directive?
use HostListener to listen to events
#HostListener('mouseover')
onMouseOver() {
this.backgroundColor = '#fff';
}
#HostListener('mouseout')
onMouseOut() {
this.backgroundColor = '#000';
}
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '#angular/core';
#Directive({
selector: '[appHover]'
})
export class HoverDirective implements OnInit {
#HostListener('mouseenter') onMouseEnter(){
this.renderer2.setStyle(this.elRef.nativeElement,'fontSize','100px')
this.renderer2.setStyle(this.elRef.nativeElement,'color','#fff')
this.renderer2.setStyle(this.elRef.nativeElement,'backgroundColor','orange')
}
#Input('appHover') case:string='';
#HostListener('mouseout') onMouseOut(){
this.renderer2.setStyle(this.elRef.nativeElement,'fontSize',this.case)
this.renderer2.setStyle(this.elRef.nativeElement,'color','#fff')
this.renderer2.setStyle(this.elRef.nativeElement,'backgroundColor','orange')
}
constructor(private elRef:ElementRef,private renderer2:Renderer2) { }
ngOnInit(): void {
}
}
goto app.component.html
then use directive.

Angular Dynamic Components - Add Class and other attributes

I am using the following code for creating the dynamic components
import {
Component, OnInit, ViewContainerRef, ViewChild, ViewChildren,
ReflectiveInjector, ComponentFactoryResolver, ViewEncapsulation, QueryList, Input, AfterViewInit
} from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { forEach } from '#angular/router/src/utils/collection';
import { IComponent } from 'app/app.icomponent';
#Component({
encapsulation: ViewEncapsulation.None,
selector: 'dynamic-component',
entryComponents: [HomeComponent, HighlevelSignalComponent],
template: `
<div #dynamicDiv [ngClass]="classFromMenu" >
<ng-template #dynamicComponentContainer></ng-template>
</div>
`,
styleUrls: [
'./dynamic-content.component.css'
],
})
export class DynamicComponent implements IComponent, OnInit, AfterViewInit {
classFromMenu: any;
#ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver, private route: Router,
private activatedRoute: ActivatedRoute, ) {
}
.......
buildComponent(passedData) {
// orderAndObjs has the data for creating the component
this.orderAndObjs.forEach(obj => {
var componentFactory = this.resolver.resolveComponentFactory(obj.component);
var compRef = this.dynamicComponentContainer.createComponent(componentFactory);
// compRef is the component that is created.
//Assuming the component that i am trying to create is <dynamic-component>.
//I want to add either a class or any other attribute like this
//<dynamic-component class="flex">
});
}
}
}
The dynamic-component is created perfectly fine and everything is working as expected. But the only issue is I want to add a class for dynamic-component so that it can be
<dynamic-component class="dynamicClass">
Any help is appreciated :(
Hmm.. I usually add it to the selector of component that is supposed to be an entryComponent ...
selector: 'dynamic-component.someclass',
^^^^^^^^^^^
to add attribute use attribute selector:
selector: 'dynamic-component[myattr=value]',
I call it hidden feature of entryComponents
but its declarative approach and can't be changed at runtime(indeed we can change it)
In Angular 5/6, using Renderer2 from #angular/core, you can do something like below:
constructor(private resolver: ComponentFactoryResolver, private route: Router,
private activatedRoute: ActivatedRoute, private renderer2: Renderer2) {
}
buildComponent(passedData) {
this.orderAndObjs.forEach(obj => {
var componentFactory = this.resolver.resolveComponentFactory(obj.component);
var compRef = this.dynamicComponentContainer.createComponent(componentFactory);
this.renderer2.addClass(compRef.location.nativeElement, 'flex');
});
}
High-level DOM operations are performed with Renderer2 provider. Considering that it was injected, it is:
this.renderer2.addClass(compRef.location.nativeElement, 'dynamicClass');
It should be noticed that depending on how dynamic element is attached to DOM, this may be unnecessary complication.
Considering that dynamicComponentContainer is real DOM element and not <ng-template>, the view of dynamic component can be directly mounted to the container, thus eliminating <dynamic-component> wrapper element:
Given the container:
<div class="dynamicClass" #dynamicComponentContainer></div>
It will be:
var compRef = componentFactory.create(
this.injector,
[],
this.dynamicComponentContainer.element.nativeElement
);

Resources