move html code to a seperate html document in Angular CLI - html

How do I move my html section from app.compontent.ts to a seperate html documenet? It wont work to just att the html code into the generated class app.component.ts.
Also I would like to move the css section as well to seperate css document.
If someone could help me or point me to the right direction I would be greatfull
import { Component } from '#angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { OnInit } from '#angular/core';
#Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<button> my Button </button>
<h2 pButton type="button" icon="fa-check" iconPos="right">My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span>{{hero.name}}
</li>
</ul>
<hero-detail [hero]="selectedHero"></hero-detail>
`,
styles: [`
.selected {
background-color: #CFD8DC !important;
color: white;
}
.heroes {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
`],
providers: [HeroService]
})
export class AppComponent implements OnInit{
title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(private heroService: HeroService){
}
getHeroes(): void{
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
onSelect(hero: Hero): void{
this.selectedHero = hero;
}
ngOnInit(): void{
this.getHeroes();
}
}

Make use of templateUrl instead of template in Component Decorator
templateUrl - url to an external file containing a template for the
view
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Add all the code to app.component.html

create separate html and css example : home.component.html and home.component.css
in component.ts file add below code
import { Component, OnInit, TemplateRef } from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})

You can add the html code in a separate html file for example: app.component.html
Copy the template without the inside the app.component.html .
Later in your #Component make the below changes:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
})

Related

How can i angular material sidenav and header component include to dashboard with css?

I made a sidenav and header with Angular material. I just want to use it in the dashboard. Because the dashboard view requires username and password confirmation. Here is the image before adding it to the Dashboard component.
After adding it to the Dashboard component, I think the css files do not work and I get an image like this. How can I fix this?
app.component.html
<mat-drawer-container>
<mat-drawer mode="side" [opened]="sideBarOpen">
<app-sidenav></app-sidenav>
</mat-drawer>
<mat-drawer-content>
<app-header (toggleSidebarForme)="sideBarToggler()">
</app-header>
<router-outlet></router-outlet>
</mat-drawer-content>
</mat-drawer-container>
dashboard.component.html
<app-sidenav></app-sidenav>
dashboard.component.ts
import { Component } from '#angular/core';
import { HeaderComponent } from '../header/header.component';
import { SidenavComponent } from '../sidenav/sidenav.component';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent {
constructor() { }
ngOnInit(): void {
}
}
sidenav.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-sidenav',
templateUrl: './sidenav.component.html',
styleUrls: ['./sidenav.component.scss']
})
export class SidenavComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}

How to change this template driven form to Reactive form in Angular?

How to change this template driven form to Reactive form? I want to change this template driven form to reactive form. What changes shall I do to change it to Reactive form? The code is complete no other modification is required? Can someone please help me with this, I am attaching all the required codes. What things we should keep in mind while changing to reactive form, also why reactive form is preferred over template driven form?
HTML code
<html>
<body>
<nav>
<div class = "navbar-header">
Image Change on clicking Enter in TextBox
<input class = "col" type = "text" readonly value ="{{imgNumber}}/3 {{cityImageId}}">
</div>
</nav>
<div class = "textarea" contenteditable #scrollDiv [scrollTop]="scrollDiv.scrollHeight" wrap="hard">
<img contenteditable="false" [src]="imagePath" width = "1090px" height = "440"/>
</div>
<form>
<div>
<input type = "text" class="col2" [(ngModel)]="pincode" (keyup.enter)="generatecityDetailArray()" maxlength="6" [ngModelOptions]="{standalone: true}"/>
</div>
</form>
<div>
<input type = "label" class = "col3" value = "Pin Code" readonly />
</div>
</body>
</html>
CSS code
nav {
background-color:black;
border : 0;
}
.navbar-header{
text-align: center;
}
.navbar-header{
color:white;
}
.col{
margin-left: 950px;
text-align: right;
border : 0;
background-color:rgb(160,0,0);
}
.textarea{
overflow: scroll;
height: 400px;
width:1090px;
background-color:white;
margin-left: 100px;
margin-top: 50px;
object-fit: none;
object-position: 1000px 200px;
}
.col2{
width:230px;
height: 30px;
margin-top: 20px;
margin-left: 950px;
}
.col3{
width:230px;
height: 30px;
margin-top: 20px;
margin-left: 950px;
}
TypeScript Code
import { Component, OnInit } from '#angular/core';
import { CityClassificationService } from 'src/app/service/city-classification.service';
#Component({
selector: 'app-city-classification',
templateUrl: './city-classification.component.html',
styleUrls: ['./city-classification.component.css']
})
export class CityClassificationComponent implements OnInit {
imgNumber : number =-1;
cityImageId : number = -1;
imagePath : string ='';
pincode:string='';
curImageNumber:number=0;
imageDetails:{imageName:string,cityImageId:number,imgNumber:number}[]=[];
cityDetailArray :{ pincode : string; cityImageId : number; imgNumber:number;}[] = [];
constructor(private cityService:CityClassificationService) { }
ngOnInit(): void {
this.imageDetails=this.cityService.getImageObject();
this.getNextImage(this.imageDetails[this.curImageNumber]);
}
getNextImage(imageObj:{imageName:string,cityImageId:number,imgNumber:number}):void{
this.imgNumber= imageObj.imgNumber;this.imagePath=`assets/images/${imageObj.imageName}.png`;this.cityImageId=imageObj.cityImageId;
}
generatecityDetailArray():void{
if(this.pincode=='' || this.pincode.toString().length>6){alert('Enter Valid PinCode');return;};
this.cityDetailArray.push(
{pincode:this.pincode, cityImageId:this.cityImageId, imgNumber:this.imgNumber}
);
this.pincode='';
this.curImageNumber++;
if(this.curImageNumber==this.imageDetails.length){this.submitForm();return;}
this.getNextImage(this.imageDetails[this.curImageNumber]);
}
submitForm(){
//TODO here....
this.cityService.getAPi(this.cityDetailArray);
}
}
Model class
export class CityClassification{
pinCode : string;
cityImageId : number;
imgNumber:number;
constructor(pinCode : string, cityImageId : number,imgNumber:number){
this.pinCode = pinCode;
this.cityImageId = cityImageId;
this.imgNumber = imgNumber;
}
}
Service class
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class CityClassificationService {
imageDetails:{imageName:string,cityImageId:number,imgNumber:number}[]=[
{imageName:'Ghazipur1',cityImageId:101,imgNumber:1},
{imageName:'Nashik2',cityImageId:102,imgNumber:2},
{imageName:'Noida3',cityImageId:103,imgNumber:3}
]
constructor() { }
getAPi(formBody:any){
//API TO SUBMIT FORM.....
console.log('INSIDE SERvice.......',formBody);
}
getImageObject():any{
//API HERE TO GET IMAGE
return this.imageDetails;
}
}
here is a simple code snippet for you,
Lets say you have component name as AppComponent,
import { Component } from '#angular/core';
import {
FormBuilder,
FormGroup,
FormControl,
Validators
} from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'stackoverflow-examples';
declare MultipleSelect: any;
textInputForm: FormGroup;
get textInputControl() {
return this.textInputForm.get('textInputControl') as FormControl;
}
constructor(
private fb: FormBuilder
) {
this.textInputForm = new FormGroup(
{
textInputControl: new FormControl('', [Validators.maxLength(6)])
}
);
}
ngOnInit() {
}
onClick(): void{
// Just to show you that form can read the values,
console.log(this.textInputForm.getRawValue());
}
}
Your Html can look like this below,
<form>
<label>
Input Name:
<input type="text" class="col2" [formControl]="textInputControl" maxLength="6"/>
</label>
</form>
<button (click)="onClick()">Click</button>

in dynamic div - on click highlight color

HTML
<div class="nav--small nodeLevel newColor" id="rowItem-{{i}}" *ngFor="let root of rootzTemplates; let i=index" (click)="nodeClickLevel1(root,i)">
<p style="padding: 19px 1px;color: #fff; text-align: center;">
{{root}}
</p>
</div>
CSS
.activeColor {
background-color: grey;
}
JavaScript
constructor(private el: ElementRef) { }
nodeClickLevel1(root, id){
this.myTag = this.el.nativeElement.querySelector("#rowItem-" + id);
this.myTag.classList.remove('activeColor');
this.myTag.classList.add('activeColor');
}
Now div is dynamic, say number of div element is 6, on click event i have to change particular clicked div background-color to grey and rest of color should remain same.
Now if I click on div say 2, only 2nd div has highlight with grey color, rest of the color should remain same and vice versa.
Change your function like this
nodeClickLevel1(root, id){
this.myTag = root
}
change your template code like this
[class.newColor]="root === myTag"
Hope it will solve your problem.
Your code can be much simpler, no need for troublesome ElementRef, no need for index ids, etc.
So here is the code:
//our root app component
import { Component, NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
#Component({
selector: 'my-app',
// templateUrl: "app.html",
template: `
<div class="nav--small nodeLevel newColor" [class.activeColor]="root === myTag" *ngFor="let root of rootzTemplates" (click)="nodeClickLevel1(root)">
<p style="padding: 19px 1px;color: #fff; text-align: center;">{{root}}</p>
</div>
`,
})
export class App {
name: string;
constructor() { }
protected myTag:any;
public rootzTemplates: any[] = ["first", "2nd", "3rd"];
nodeClickLevel1(root){
this.myTag = root;
}
}
#NgModule({
imports: [BrowserModule],
declarations: [App],
bootstrap: [App],
})
export class AppModule {}
and css:
.activeColor {
background-color: grey !important;
}
.nav--small{
background-color: black;
}
Here is the working PLNKR link:
http://plnkr.co/edit/oRZa3E5WtYpusKHd

angular custom css class is not appening in view

I am working on angular formio, in that I am using a custom css class, name CustomCSS I have added the same in css file as follows
Here is stackblitz
app.component.scss
.CustomCSS {
margin: auto;
width: 50%;
border: 3px solid rgb(1, 248, 1);
padding: 10px;
background-color: coral;
}
app.component.ts
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
ngOnInit() {
debugger;
this.triggerRefresh = new EventEmitter();
this.http.get('http://....')
.subscribe(
response => {
this.form = response.json();// this is my html script from DB
},
err => {console.error(err)}
);
}
}
app.component.html
<formio [refresh]="triggerRefresh" [form]="form" [submission]="submission" (submit)="onSubmit($event)"></formio>
My Html this.form script as follows
{
"components":[
{
"label":"City",
"widget":"choicesjs",
"customClass":"CustomCSS",
"tableView":true,
"data":{
"values":[
{
"label":"abc",
"value":"abc"
]
},
"selectThreshold":0.3,
"calculateServer":false,
"validate":{
"required":true
},
"key":"city",
"type":"select",
"indexeddb":{
"filter":{
}
},
"input":true
},
{
"type":"button",
"label":"Submit",
"key":"submit",
"disableOnInvalid":true,
"input":true,
"tableView":false
}
],
"id":4
}
In my script also the css class name available but it is not appending in the view.
One possible way to make it work from your component is to modify the style encapsulation for that component.
import { Component, OnInit, ViewEncapsulation } from '#angular/core'; // <-- add ViewEncapsulation
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
encapsulation: ViewEncapsulation.None // <-- add this line
})
More information on encapsulation.
That being said.
I still recommend to use global styles and implement css selectors to target formio generated html elements like in your example:
#app formio .control-label {
font-weight: bold;
}

Why CSS doesn't match with Angular 6 selector component?

app.html
<app-chat></app-chat>
chat.html
<h1>Hello</h1>
chat.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
chat.css
h1 {
background-color: #000;
}
I need to know why the chat.css doesn't work in my browser. When I used CSS directly without chat component it works (like below).
app.html
<h1>Hello</h1>
app.css
h1 {
background-color: #000;
}
So what is the solution?
Try this!
::ng-deep h1{
background-color: #000;
}
Try !important in your chat.css file
h1{
background-color: #000 !important;
}
or
Use the powerful weapon of CSS style.css. But, before using it you have to set the class name for h1 tag.
chat.html
<h1 class="exampleClassName">Helo<h1>
Next, in your style.css file
.exampleClassName{
background-color: #000;
}
I did an example and it works: https://stackblitz.com/edit/angular-u99pry