html wont render from inside angular 2 component - javascript

I'm using a service to dynamically change the content in my header depending on the page I'm on, however when I put HTML in my component it doesn't render in the browser (see example below)
home.component.ts
import { Component, OnInit } from '#angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(
private headerTitleService: HeaderTitleService
) { }
ngOnInit() {
this.headerTitleService.setTitle(`
We strive to create things
<br> that are engaging, progressive
<br> & above all
<span class="highlight">
<em>innovative.</em>
</span>
`);
}
}
header.component.ts
import { Component, OnInit } from '#angular/core';
import { HeaderTitleService } from '../../../services/headerTitle.service'
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
title: any;
constructor(
private headerTitleService: HeaderTitleService
) { }
ngOnInit() {
this.headerTitleService.title.subscribe(updatedTitle => {
this.title = updatedTitle;
});
}
}
header.component.html
<h1>{{title}}</h1>
so Im trying to set the title to be a string that has html tags in it that I want to be rendered but what happens is the whole thing comes out as a string instead of how it would look like it I had put it in my home.component.html.
Is there a way I can do this??

You can set the [innerHtml] property
<h1 [innerHtml]="title"></h1>
Example

Related

unable to pass data between one component to another component in angular

I am trying to pass data from one component to another component I used the service file method.
I created two components one is login and the second is home. I have to pass data from login to home.
in the login component, I take user input, and the home component should print that.
I used this code below, but when I give input, it is not printing in output.
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class SharedService {
message : any;
constructor() { }
setMessage(data: any){
this.message=data;
}
getMessage(){
return this.message;
}
}
this is my home component code
import { Component, OnInit } from '#angular/core';
import { SharedService } from '../shared/shared.service'
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
message : string | undefined;
constructor(private shared:SharedService ) {}
ngOnInit() {
this.message =this.shared.getMessage()
}
}
<h1> {{ message }} </h1>
this is my login component code
import { Component, OnInit } from '#angular/core'
import { SharedService } from "../shared/shared.service"
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
message : any ;
constructor(
private shared: SharedService
) { }
ngOnInit(): void {
this.shared.setMessage(this.message)
}
}
<input required type="text" class="form-control" placeholder="Enter username" [(ngModel)]="message">
ofcourse it will not work this way .the reason it is not working . when you call SharedService in your constructor in box component it create an instance of your service with message : any . if you change it on one component it will not change on the other component .
what you can do is .
on your service . message = new Subject() ; setMessage(data: any){ this.message.next(data) ; }
you call set message on your login component . and on your home component you subscribe to the subject like this . this.sharedService.getMessage().subscribe( (result :any ) => {console.log(result )} .
sorry if this answer is messy , this is my first time using SOF .

Cannot display Angular dialog properly

I am trying to make a dialog box in Angular, but the dialog is not been displayed in the centre, only as a vertical white rectangle to the left.
I will include an image depicting the exact problem: screenshot of the page.
I have included entry components in my appmodule.ts file
There are no errors while compiling it.
Header component.ts file :
import { Component, OnInit } from '#angular/core';
import { MatDialog, MatDialogRef } from '#angular/material';
import { LoginComponent } from '../login/login.component';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
constructor(public dialog: MatDialog ) { }
ngOnInit() {
}
openLoginForm() {
this.dialog.open(LoginComponent, {width: '500px', height: '450px'});
}
}
add LoginComponent in entrycomponents array in module.
like this.
entryComponents: [LoginComponent]

Angular app is compiling successfully but giving errors property does not exist in 'ng build --prod'

Angular app is compiling successfully but giving the following errors in 'ng build --prod'
ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent'.
src\app\dashboard\dashboard.component.html(3,72): : Property 'newsService' is private and only accessible within class 'DashboardComponent'.
src\app\dashboard\dashboard.component.html(3,72): : Property 'p' does not exist on type 'DashboardComponent'.
src\app\dashboard\dashboard.component.html(29,46): : Property 'p' does not exist on type 'DashboardComponent'.
I have used these properties in my html file as below:
header.component.htmlfile
<input type="text" class="form-control mr-2 align-self-center" required placeholder="Search" name="searchText" [ngModel]="searchText" value="">
dashboard.component.htmlfile
<pagination-controls class="text-center" (pageChange)="p = $event"></pagination-controls>
my header.component.html file
import { Component, OnInit, Output, EventEmitter, ViewEncapsulation } from '#angular/core';
import { NgForm } from '#angular/forms';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
filterText : string;
#Output() search = new EventEmitter();
#Output() filterButton = new EventEmitter();
constructor() { }
ngOnInit() {
}
onSubmit(form : NgForm)
{
console.log(form);
this.search.emit(form);
}
filterClicked($event)
{
this.filterText = $event.target.text;
this.filterButton.emit(this.filterText);
}
}
my dashboard.component.html file
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { NewsService } from '../shared/news.service';
import { NewsModel } from '../shared/news.model';
import { Form } from '#angular/forms';
import { Pipe, PipeTransform } from '#angular/core';
import { element } from 'protractor';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
articles : any;
temp : NewsModel = new NewsModel;
constructor(private newsService : NewsService) { }
ngOnInit() {
this.FetchHeadlines();
}
FetchHeadlines()
{
this.newsService.GetAllGaurdian()
.subscribe((result) =>
{
this.articles = result;
this.articles.response.results.forEach(element => {
this.newsService.newsArticles.push(this.newsService.CusotomMapper(element));
});
})
}
}
can't able to figure out where is the error exactly!
I think the error descriptions are as accurate as it can be. each of them tells you that something wrong with your component, lets examine each of them
ERROR:
ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent'.
you have searchText in HeaderComponent HTML, but not in the Component itself
SOLUTION: add searchText variable to the Component
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
searchText:string
...
}
ERROR :
src\app\dashboard\dashboard.component.html(3,72): : Property 'newsService' is private and only accessible within class 'DashboardComponent'.
all the fields you are using inside the template, must be the public field inside component itself, otherwise it will not compile
SOLUTION: change private modifier to public at newService
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor(public newsService : NewsService) { }
...
}
ERRORS :
src\app\dashboard\dashboard.component.html(3,72): : Property 'p' does not exist on type 'DashboardComponent'.
src\app\dashboard\dashboard.component.html(29,46): : Property 'p' does not exist on type 'DashboardComponent'.
same as HeaderComponent. you are using p field but it's not defined in DashboardComponent
SOLUTION : add p field to the dashboard component
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
p:any
...
}
You are trying to access from the template, variables that aren't defined in the corresponding components.
In header.component.html you are setting [ngModel]="searchText" and variable searchText isn't defined on header.component.ts. Could it be filterText variable instead?
In dashboard.component.html you are setting p = $event and variable p isn't defined on dashboard.component.ts. You also have an error about newsService being private. If you are gonna use it in the template it must be declared public when you inyect it on the constructor. I hope this helps. If you need more help is better if you provide a Stackblitz with minimum code.

How to update other component html text value

This is my app.component.html source code:
<split-flap></split-flap>
<button (click)="flip('+')">+</button><button (click)="flip('-')">-</button>
This is my app.component.ts source code:
import { Component } from '#angular/core';
import { SplitFlapComponent } from './split-flap/split-flap.component';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers:[SplitFlapComponent]
})
export class AppComponent {
constructor(private splitFlapComponent: SplitFlapComponent)
{
}
flip(flag)
{
console.log(flag);
this.splitFlapComponent.title=flag;
}
}
This is my split-flap.component.ts:
import { Component, OnInit, Input, Output } from '#angular/core';
#Component({
selector: 'split-flap',
templateUrl: './split-flap.component.html',
styleUrls: ['./split-flap.component.css']
})
export class SplitFlapComponent implements OnInit {
title: string;
constructor() {
this.title = 'split-flap works1!';
}
ngOnInit() {
}
}
This is my split-flap.component.html:
<p>{{title}}</p>
My app.component.html has two buttons, both of them pass a sign to split-flap.component, would you tell me how can I the update split-flap.component.html content? Because most of the examples for input box only, I cannot find an example for <p>.
Try like this:
Solution 1 : #Input()
app.component.html
<split-flap [title]="title"></split-flap>
app.component.ts
title: string;
constructor() {
this.title = 'split-flap works1!';
}
flip(flag)
{
console.log(flag);
this.title=flag;
}
split-flap.component.ts:
#Input() title: string
Solution 2 : ViewChild()
app.component.html
<split-flap #child ></split-flap>
app.component.ts
#ViewChild('child') child: SplitFlapComponent ;
flip(flag)
{
console.log(flag);
this.child.title=flag;
}

Theme switcher on localstorage observable service

I implemented a dynamic theme switcher (with tutorial) in my angular app. It work's but when I reload website, the choice is not remembered.
I read about localStorage and i will use it but still doesn't work because I don't know how "where" I should get data from this localStorage, that the choice of the theme will be remembered when I reload the page.
I have this code:
theme.service.ts new version
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class ThemeService {
private _themeDark: Subject<boolean> = new Subject<boolean>();
isDarkFunction() {
let value = localStorage.getItem('isDark');
this._themeDark.next(value);
return this._themeDark.asObservable();
}
isThemeDark = this.isDarkFunction();
setDarkTheme(isThemeDark: boolean) {
this._themeDark.next(isThemeDark);
localStorage.setItem('isDark', JSON.stringify(isThemeDark));
}
}
navbar.component.html
<div class="container-fluid switcher-container">
<mat-slide-toggle [checked]="isThemeDark | async" (change)="toggleDarkTheme($event.checked)">Dark theme</mat-slide-toggle>
</div>
navbar.component.ts
import { Component, OnInit } from '#angular/core';
import { ThemeService } from '../services/theme.service';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
isThemeDark: Observable<boolean>;
constructor(
private themeService: ThemeService) { }
ngOnInit() {
this.isThemeDark = this.themeService.isThemeDark;
}
toggleDarkTheme(checked: boolean) {
this.themeService.setDarkTheme(checked);
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Observable } from "rxjs/Observable";
import { ThemeService } from "./services/theme.service";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [ThemeService]
})
export class AppComponent implements OnInit {
isThemeDark: Observable<boolean>;
constructor(
public themeService: ThemeService) {
}
ngOnInit() {
this.isThemeDark = this.themeService.isThemeDark;
}
}
Please help,
Regards
You might write something like the following in theme.service.ts.
I don't know if it will run flawlessly as is but the idea is to read from localstorage in isThemeDark().
isThemeDark() {
let value = localStorage.getItem('isDark');
this._themeDark.next(value);
return this._themeDark.asObservable();
}
I think it's because you when you do localStorage.getItem('isDark') the result is a string, not a boolean. Maybe try:
let value = JSON.parse(localStorage.getItem('isDark')) === true;
Also check manually if the localstorage is kept after a refresh. Some browsers have a setting to clear everything on refresh.

Categories

Resources