Adding a component into a div - html

I am trying to create a div and then add a component into that div during runtime. I was wondering how i could do this.
this is my components html:
<p>
<label >name</label>
</p>
this is my components ts :
import { Component, OnInit} from '#angular/core';
#Component({
selector: 'app-newcomp',
templateUrl: './newcomp.component.html',
styleUrls: ['./newcomp.component.css']
})
export class NewcompComponent implements OnInit {
name: string;
constructor() {
}
ngOnInit() {
}
}
This is where it will be called
import { Component } from '#angular/core';
import { NewcompComponent } from './newcomp/newcomp.component';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor() {
this.Newcomp();
}
Newcomp() {
const div = document.createElement('div');
document.body.appendChild(div);
<-- this is where the component is added to the div, how can i achieve this.
}
}
If someone could help me it would be greatly appreciated. :)
Also i know this example is simple, but keeping it simple will allow for clarity in the answer.

import { Component } from '#angular/core';
import { NewcompComponent } from './newcomp/newcomp.component';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
component: Type<any>;
constructor() {
this.component = this.newcomp();
}
private newcomp() {
// use this method for logic
return NewcompComponent;
}
}
In app.component.html add:
<ng-container *ngComponentOutlet="component"></ng-container>
For more info Angular's component outlet info & Angular's dynamic component creation

Related

AOS animation how to implement in ionic using angular framework?

import { Component, OnInit } from '#angular/core';
*import * as AOS from 'aos';*
#Component({
selector: 'app-component',
templateUrl: './app-component.component.html',
styleUrls: ['./app-component.component.scss'],
})
export class AppComponent implements OnInit {
constructor( ) { }
ngOnInit() {
*AOS.init();*
}
I'm using this way but not working yet.If it's possible or not?

Angular, how to display more than one random quote on one page?

I am a beginner in Angular (12) and I am struggling with this issue. I want to display more than one random quote on a page. I've managed to display multiple, but they are all the same underneath eachother. I have no errors in the code. I have tried some forEach but couldn't do it. Here is the code:
app.component.html
<div class="main-content">
<div class="joke-wrapper" *ngFor="let joke of jokes">
<div class="joke">
<p>{{ joke.value }}</p>
</div>
</div>
<div class="joke-wrapper" *ngFor="let joke of jokes">
<div class="joke">
<p>{{ joke.value }}</p>
</div>
</div>
</div>
jokes.service.ts:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root',
})
export class JokesService {
private apiUrl = 'https://api.chucknorris.io/jokes/';
constructor(private http: HttpClient) {}
getRandomJoke() {
return this.http.get(this.apiUrl + 'random');
}
}
app.component.ts:
import { Component, OnInit } from '#angular/core';
import { JokesService } from './jokes.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
jokes: any[] = [];
constructor(private jokesService: JokesService) {}
ngOnInit() {
this.jokesService.getRandomJoke().subscribe((joke) => {
this.jokes.push(joke);
});
}
}
The problem is that your array only contains one joke.
This probably works.
import { Component, OnInit } from '#angular/core';
import { JokesService } from './jokes.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
jokes: any[] = [];
constructor(private jokesService: JokesService) {}
ngOnInit() {
// Multiple times
this.addJoke();
this.addJoke();
}
addJoke() {
this.jokesService.getRandomJoke().subscribe((joke) => {
this.jokes.push(joke);
});
}
}
Although I would prefer this solution:
Making use of the async pipe can get some performance gains and it is generaly cleaner code.
component ts:
import { Component, OnInit } from '#angular/core';
import { JokesService } from './jokes.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
jokes$!: Observable<any[]>;
constructor(private jokesService: JokesService) {}
ngOnInit() {
this.jokes$ = this.jokesService.getRandomJokes(10);
}
}
Service ts:
#Injectable({
providedIn: 'root',
})
export class JokesService {
private apiUrl = 'https://api.chucknorris.io/jokes/';
constructor(private http: HttpClient) {}
getRandomJoke() {
return this.http.get(this.apiUrl + 'random');
}
getRandomJokes(amount: number) {
const jokes = [];
for (let i = 0; i < amount; i++) {
jokes.push(this.getRandomJoke())
}
return forkJoin(jokes);
}
}
component html:
<div class="main-content">
<div class="joke-wrapper" *ngFor="let joke of jokes$ | async">
<div class="joke">
<p>{{ joke.value }}</p>
</div>
</div>
</div>

ERROR TypeError: _co.getAdmin is not a function

This is an Angular application and it's something wrong with function getAdmin() in auth.service, but I have no idea what. When I moved this function to app.component.ts and changed to "getAdmin()" in HTML, it was OK, but I need this function in service. Please tell me what's wrong and how can I fix it.
PS. variable admin returns 'true' or 'false' as a string.
It's e-Commerce app with user authentication, token and now I try to add admin.
auth.service.ts:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient, private _router: Router) { }
getAdmin() {
if (localStorage.getItem('admin') === 'true') return true;
return false;
}
}
app.component.ts:
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _authService: AuthService) {
}
}
app.component.html:
<a class="nav-link" *ngIf="_authService.getAdmin()" routerLink="/admin" routerLinkActive="active">Admin</a>
It's always better to not call a function written in service from html . I think, you can resolve your current issue by changing your service scope from private to public. But the best way is to call a function inside component from html and call the getAdmin() inside service from that function. The best practise is to keep the service scope to private itself while doing dependency injection.
app.component.html
<a class="nav-link" *ngIf="adminExists()" routerLink="/admin" routerLinkActive="active">Admin</a>
app.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient, private _router: Router) { }
getAdmin() {
if (localStorage.getItem('admin') === 'true') return true;
return false;
}
}
app.component.ts
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _authService: AuthService) {
}
adminExists(){
return _authService.getAdmin();
}
}
Change scope of service private to public in app.component.ts:
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public _authService: AuthService) {
}
}

Calling a function between components

I have two components(comp1 and comp2). I am trying to call a function which is inside comp1 from comp2 and it is not happening and it is throwing an error. But it is successful when calling a function inside comp2 from comp1.
I want it to happen in both the ways
(i.e)
(a) function trigger from comp2 inside comp1
(b)function trigger from comp1 inside comp2
I have attached the sample code.
https://stackblitz.com/edit/angular-jxfzqb
The error is throwing from constructor function on comp1, it cant generate a new instance of comp2.
Please try not use provides of components between components, i suggest you make getting binding components from app.component to comp1 and comp2, example:
app.component.html
<app-comp1 #comp1 [Comp2Component]="comp2"></app-comp1>
<app-comp2 #comp2 [Comp1Component]="comp1"></app-comp2>
app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Comp1Component } from './comp1/comp1.component';
import { Comp2Component } from './comp1/comp2/comp2.component';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
// Get component with attr #comp1
#ViewChild('comp1') comp1: Comp1Component;
// Get component with attr #comp2
#ViewChild('comp2') comp2: Comp2Component;
}
comp1.component.ts
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.css']
})
export class Comp1Component implements OnInit {
#Input() Comp2Component: Comp2Component;
constructor() { }
ngOnInit() {
}
funcInComp1() {
console.log("comp1 function triggered from comp2");
}
triggerComp2Function() {
this.Comp2Component.funcInComp2();
}
}
comp2.component.ts
import { Input, Component, OnInit } from '#angular/core';
import { Comp1Component } from '../comp1.component';
#Component({
selector: 'app-comp2',
templateUrl: './comp2.component.html',
styleUrls: ['./comp2.component.css']
})
export class Comp2Component implements OnInit {
#Input() Comp1Component: Comp1Component
constructor() { }
ngOnInit() {
}
triggerComp1Function() {
this.Comp1Component.funcInComp1();
}
funcInComp2() {
console.log("comp2 function triggered from comp1");
}
}
stackblitz:
https://stackblitz.com/edit/angular-itmzhe

Angular 2/4: Can't update child component view

I want to update the value of str which I used in the view of child component from the parent component, by calling the function change() of child component
here is my code.
import { Component } from '#angular/core';
import { ChildComponent } from './child/child.component';
#Component({
selector: 'app-root',
template: `
<h1>parent</h1>
<button (click)="changeChild()">change child</button>
<app-child></app-child>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private cc:ChildComponent) {}
changeChild(){
this.cc.change();
}
}
and the child component is:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-child',
template: `
<p>{{str}}</p>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
private str;
constructor() {
this.str = 'initial'
}
change(){
this.str = 'changed'
}
ngOnInit() {
}
}
but the value str in the view never updated to "changed".
please Any help because I am new in Angular 4 ??
Use #ViewChild to get reference of child component
in Parent component
import {ChildComponent} from 'child.component.ts'
export class ParentComponent{
------
#ViewChild(ChildComponent)
private child:ChildComponent
---
changeChild(){
this.child.change()
}
}