Accessing innerText inside Component - html

I'm having pretty simple component that looks like this and basicly does the job.
import { Component, Input } from '#angular/core';
#Component({
selector: 'app-code',
template: ' <pre><code [highlight]="code" [languages]="languages" [lineNumbers]="true"></code></pre> '
})
export class CodeComponent {
readonly languages = ['java'];
#Input()
code = '';
constructor() {
}
}
But, I'd like to make minor change to it
#Component({
selector: 'app-code',
template: '<pre><code [highlight]="code" [languages]="languages" [lineNumbers]="true"></code></pre>'
})
export class CodeComponent {
readonly languages = ['java'];
code = '';
constructor(private elem: ElementRef) {
this.code = elem.nativeElement.innerText;
}
}
So instead of writing
<app-code [code]="'some code goes here'"></app-code>
I can write
<app-code>some code goes here</app-code>
Unfortunatelly, It's not working, my code block remains empty

You cannot get innerText because CodeComponent is not drawn.
You need to use ngAfterViewInit.
#Component({
selector: 'app-code',
template: '<pre><code [highlight]="code" [languages]="languages" [lineNumbers]="true"></code></pre>'
})
export class CodeComponent {
readonly languages = ['java'];
code = '';
constructor(private elem: ElementRef) {
}
ngAfterViewInit() {
this.code = elem.nativeElement.innerText;
}
}

Related

Update embedded Swagger UI on toggle button change

I want to provide three different OpenApi definitions in a webapp, so users can read the documentation of different APIs.
The plan is to have a toggle button group with three buttons at the top and the swagger ui underneath it.
My problem is, that the swagger ui won't update if I click on a button. My approach looks like this:
api-docs.component.html
<mat-card>
<mat-button-toggle-group style="width: auto; display: flex;" (change)="toggleApiDoc($event)">
<mat-button-toggle checked value="mainPlattform" style="width: 100%">Main Plattform</mat-button-toggle>
<mat-button-toggle value="adapterHttp" style="width: 100%">Adapter HTTP</mat-button-toggle>
<mat-button-toggle value="adapterMqtt" style="width: 100%">Adapter MQTT</mat-button-toggle>
</mat-button-toggle-group>
<app-swagger-ui [url]=activeApiDoc></app-swagger-ui>
</mat-card>
api-docs.component.ts
import { Component } from '#angular/core';
import { MatButtonToggleChange } from '#angular/material/button-toggle';
import { environment } from 'src/environments/environment';
#Component({
selector: 'app-api-docs',
templateUrl: './api-docs.component.html',
styleUrls: ['./api-docs.component.scss']
})
export class ApiDocsComponent {
readonly mainApiDoc = environment.main_api_doc;
readonly httpAdapterApiDoc = environment.http_adapter_doc;
readonly mqttAdapterApiDoc = environment.http_adapter_doc;
activeApiDoc = this.mainApiDoc;
constructor() {
}
toggleApiDoc(event: MatButtonToggleChange) {
switch (event.value) {
case 'mainPlattform':
this.activeApiDoc = this.mainApiDoc;
break;
case 'adapterHttp':
this.activeApiDoc = this.httpAdapterApiDoc;
break;
case 'adapterMqtt':
this.activeApiDoc = this.mqttAdapterApiDoc;
break;
default:
this.activeApiDoc = this.mainApiDoc;
break;
}
}
}
swagger-ui.component.html
<div id="swagger"></div>
swagger-ui.component.ts
import { Component, Input, OnInit } from '#angular/core';
import SwaggerUI from 'swagger-ui';
#Component({
selector: 'app-swagger-ui',
templateUrl: './swagger-ui.component.html',
styleUrls: ['./swagger-ui.component.scss']
})
export class SwaggerUiComponent implements OnInit {
#Input() url: string = "";
constructor() { }
ngOnInit(): void {
const ui = SwaggerUI({
url: this.url,
dom_id: '#swagger'
});
}
}
environment.ts
export const environment = {
main_api_doc: 'https://petstore.swagger.io/v2/swagger.json',
http_adapter_doc: 'https://raw.githubusercontent.com/hjacobs/connexion-example/master/swagger.yaml'
};
As you can see I use random yaml files to test this. The first one gets rendered. I have an complete Swagger UI embedded in my webapp, but it won't render another Swagger UI, when I click a different toggle button. It just stays the same.
As you can tell, I'm not so good with typescript and angular. So I guess it shouldn't be too hard. But I can't tell whats wrong here.
The problem seems to be the angular lifecycle. When I tried to view all docs at the same time I saw that still only one would get rendered.
I changed the lifecycle hook function, where I create the Swagger UI and now it works.
import { Component, Input, OnChanges } from '#angular/core';
import SwaggerUI from 'swagger-ui';
#Component({
selector: 'app-swagger-ui',
templateUrl: './swagger-ui.component.html',
styleUrls: ['./swagger-ui.component.scss']
})
export class SwaggerUiComponent implements OnChanges {
#Input() url: string = "";
constructor() { }
ngOnChanges() {
const ui = SwaggerUI({
url: this.url,
dom_id: '#swagger'
});
}
}

Angular innerHtml

I am relative new in Angular and I have the following question.
I have a component: my.component.html
<app-loading *ngIf="loading" message="Inhalt wird geladen..." delay="0"></app-loading>
<div [innerHtml]="content | safeHtml"></div>
And the following ts file: my.component.ts
export class MyComponent implements OnInit {
loading: boolean;
#Input() serviceUrl: string;
content: string;
constructor(public service: MyService) { }
ngOnInit() {
this.loading = true;
this.content = '';
this.service.getMyContent(this.serviceUrl).then(myContent => this.onMyContentRead(myContent));
}
onMyContentRead(dto: SimpleDto) {
this.loading = false;
this.content = dto.output;
}
}
It calls a REST service and gets the dto.output, which is a string contains the following html content from MyClassToShow.html
<li id="myBox_panels">
%s
<app-tooltip [myText]="test"></app-tooltip>
</li>
The tooltip components exists, and looks like this:
#Component({
selector: 'app-tooltip',
template: `
<a class="help" [pTooltip]="myText" [tooltipPosition]="tooltipPosition" </a>
})
export class TooltipComponent implements OnInit {
tooltipPosition: string;
#Input() myText;
constructor(private el: ElementRef) { }
ngOnInit() {
this.setTooltipPosition();
}
setTooltipPosition() {
....
}
It seems that the app-tooltip selector is not realized, because its template content is not displayed on the webpage, altough I can see the selector on the console log.
The innerHtml can only contain plain HTML code?
How can I get my app-tooltip template as well?
Thnak you a lot in advance!

Angular: ERROR TypeError: Cannot read property 'choice_set' of null, while data displayed correctly

i hope you're doing well.
I am trying to implement a FormsBuilder in Angular by accessing the data from an API. The data is pushed down to its child-component via #Input().
However the data gets pushed down, are provided and shown successfully, but still I get this Error, when the first attempt from ngOnChangess tries to receive the data.
ERROR TypeError: Cannot read property 'choice_set' of null
at StyleTypeQuestionComponent.setFormValues (style-type-question.component.ts:34)
at StyleTypeQuestionComponent.ngOnChanges (style-type-question.component.ts:26)
at StyleTypeQuestionComponent.rememberChangeHistoryAndInvokeOnChangesHook (core.js:1471)
at callHook (core.js:2490)
at callHooks (core.js:2457)
at executeInitAndCheckHooks (core.js:2408)
at refreshView (core.js:9207)
at refreshEmbeddedViews (core.js:10312)
at refreshView (core.js:9216)
at refreshComponent (core.js:10358)
The data is provided through an data-service and are subscribed through an async pipe from its parent-component and as mentioned above pushed down via property binding.
I tried to use the ? operator in my template and tried to set an Timeout on the childcomponent. Also i tried to initialize the data via default values. Still thats making no sense for me right know, because the data is already available through his parent component and getting checked via an *ngIf directive.
I hope i could provided as much as information as needed.
I guess there is an initializing problem in the first seconds of ngChanges.
Parent-Component
import { Component, Input, OnChanges, OnInit } from '#angular/core';
import { Question } from '../shared/models/question';
import { QuestionStoreService } from '../shared/question-store.service';
import { Observable } from 'rxjs';
#Component({
selector: 'pc-style-type-detection',
templateUrl: './style-type-detection.component.html',
styleUrls: ['./style-type-detection.component.css'],
})
export class StyleTypeDetectionComponent implements OnInit, OnChanges {
question$: Observable<Question>;
#Input() question_Input: Question;
question_index: number = 1;
constructor(private qs: QuestionStoreService) {}
ngOnInit(): void {
this.question$ = this.qs.getSingle(1);
}
ngOnChanges(): void {}
updateBook(question: Question): void {
console.log(question);
}
}
Parent-Template
<pc-style-type-question
*ngIf="question$"
(submitQuestion)="updateBook($event)"
[question]="question$ | async"
></pc-style-type-question>
Child-Component
import {
Component,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
} from '#angular/core';
import { FormArray, FormBuilder, FormGroup } from '#angular/forms';
import { Choice, Question } from '../shared/models/question';
#Component({
selector: 'pc-style-type-question',
templateUrl: './style-type-question.component.html',
styleUrls: ['./style-type-question.component.css']
})
export class StyleTypeQuestionComponent implements OnInit, OnChanges {
questionForm: FormGroup;
#Input() question: Question;
#Output() submitQuestion = new EventEmitter<Question>();
constructor(private fb: FormBuilder) {}
ngOnChanges(): void {
this.initForm();
this.setFormValues(this.question);
}
ngOnInit(): void {
this.initForm();
}
private setFormValues = (question: Question) => {
this.questionForm.patchValue(question.choice_set);
this.questionForm.setControl(
'choice_set',
this.buildChoiceSetArray(question.choice_set)
);
};
initForm = () => {
if (this.questionForm) {
return;
}
this.questionForm = this.fb.group({
choice_set: this.buildChoiceSetArray([
{
choice_text: '',
choice_value: false,
},
]),
});
};
get choiceSet(): FormArray {
return this.questionForm.get('choice_set') as FormArray;
}
private buildChoiceSetArray = (values: Choice[]): FormArray => {
if (values) {
return this.fb.array(
values.map((choice) => {
return this.fb.control(choice.choice_value);
})
);
}
return this.fb.array(
this.question.choice_set.map((choices) =>
this.fb.control(choices.choice_value)
)
);
};
submitForm() {}
}
Child-Template
<form class="ui form" [formGroup]="questionForm" (ngSubmit)="submitForm()">
<div
formArrayName="choice_set"
*ngFor="let choiceset of choiceSet?.controls; index as i"
>
<div>
<input type="checkbox" [formControl]="choiceset" />
<label>
{{ question.choice_set[i].choice_text }}
</label>
</div>
</div>
</form>
Thank you in advance and wish you a nice weekend.
You are not using ngOnChanges the right way, its going to be triggered everytime your input change no matter what the value is which means you need to check if that value is what you expect it to be with SimpleChanges.
ngOnChanges(changes: SimpleChanges) {
if(changes.question.currentValue) {
this.initForm();
this.setFormValues(this.question);
}
}

ViewEncapsulation.None not working with innertHTML

I'm actually developing an angular application and I have to put an [innerHTML] element in a div.
My code
Like that :
something.component.html
<section class="mx-auto" *ngFor="let publication of publication">
<div [innerHTML]="publication.content"></div>
</section>
So in ts :
something.component.ts
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { Subscription } from 'rxjs';
import { ActivatedRoute } from '#angular/router';
import { Title, Meta } from '#angular/platform-browser';
import { Publication } from '../publication.model';
import { PublicationsService } from '../publication.service';
#Component({
selector: 'app-free-publication',
templateUrl: './something.component.html',
styleUrls: ['./something.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class FreePublicationComponent implements OnInit {
publication: Publication[] = [];
suggestions: Publication[] = [];
private routeSub: Subscription;
getId: any;
isLoading = false;
constructor(public publicationsService: PublicationsService, private route: ActivatedRoute, private titleService: Title, private meta: Meta) {
this.getId = this.route.url['_value'][1].path;
this.getId = + this.getId;
}
ngOnInit() {
this.isLoading = true;
// main publication
this.routeSub = this.route.params.subscribe(params => {
this.publicationsService.getPublication(params['publicationId']).then(dataPublication => {
for (let i = 0; (dataPublication.content.match(/wp-content/g) || []).length; i++) {
dataPublication.content = dataPublication.content.replace('https://aurelienbamde.com/wp-content/', 'assets/content/');
}
this.titleService.setTitle(dataPublication.title);
this.meta.addTag({ name: 'keywords', content: dataPublication.post_tag });
this.publication = [dataPublication];
});
});
}
}
And my innertHTML do not return the style of the html doc that I send.
My tests
With a console.log() at the end of ngOnInit, I can see my html with all of the styles attributs, but by inspecting the div of the innerHTML, there is no style inside.
My question
So I well implement ViewEncapsulation.None as you see, there is an action on other elements, so it works, but not on my innerHTML.
Do you have any idea, problem of version ? Or coworking with others elements ?
Thanks in advance for your time !
And I wish you success in your projects.
You must bypass the security imposed by angular for dangerous content (HTML content not generated by the app). There is a service, called DomSanitizer that enables you to declare a content as safe, preventing angular to filter potentially harm things to be used like styles, classes, tags etc. You basically need to pass your content through this sanitizer using a pipe:
<div [innerHTML]="dangerousContent | safeHtml"></div>
Your SafeHtmlPipe would be something like this:
#Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
transform(value: string): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(value)
}
}
There are other bypassSecurityTrust* methods in DomSanitizer:
bypassSecurityTrustScript
bypassSecurityTrustStyle
bypassSecurityTrustUrl
bypassSecurityTrustResourceUrl
You can find more info in Angular docs.

Adding a chips component in Angular 4 with Typescript

I'm trying to add a chips component to my Angular web application. It's written in Typescript, HTML, and CSS files.
I've been struggling for a few weeks trying to get it right and haven't come across the right solution.
Here is a Plunkr with my current code:
https://plnkr.co/edit/zvEP9BOktwk6nBojsZQT?p=catalogue
UPDATE: I have edited my code to reflect that I am reading an input which is a string array, called selected. I am outputting a string array called code.
Below is the code that I am working with:
import {
Component, Input, HostBinding, ElementRef, ViewChild, HostListener, EventEmitter, Output, OnInit, SimpleChanges,
OnChanges, QueryList, TemplateRef, ContentChildren, Directive
} from '#angular/core';
import {ControlValueAccessor} from '#angular/forms';
import {Subject} from "#reactivex/rxjs/dist/es6/Subject";
#Component({
selector: 'chips',
templateUrl: './chips.component.html',
styleUrls: ['./chips.component.scss']
})
export class ChipsComponent implements ControlValueAccessor, OnInit{
#Output() code: string[];
#Input() type = 'text';
#Input() duplicates = false;
#Input() selected: any[];
chips: ['chip1', 'chip2', 'chip3']
chipItemList: any[];
constructor() {
}
ngOnInit() {
console.log("selected in chips component ngOnInit(): " + this.selected);
console.log("code in chips component ngOnInit: " + this.code);
}
addChip($event){
this.selected.push($event.target.value)
$event.target.value = '';
}
/*addChip(addSelectedCode) {
//this.newChips.next(this.addCode);
console.log("addCode in chips component addChip(): " + this.addSelectedCode);
if (!this.chip || !this.duplicates && this.selected.indexOf(this.chip) !== -1) return;
this.selected.push(this.chip);
this.chip = null;
this.propagateChange(this.selected);
this.selectedCodeOutput = this.addSelectedCode;
console.log("selectedCodeOutput in chips component: " + this.selectedCodeOutput);
} */
remove(index: number) {
//this.addSelectedCode.splice(index, 1);
this.propagateChange(this.selected);
this.selectedCodeOutput = this.addSelectedCode;
}
/*
Form Control Value Accessor
*/
writeValue(value: any) {
if (value !== undefined) this.selected = value;
}
propagateChange = (_: any) => {
};
registerOnChange(fn: any) {
this.propagateChange = fn;
}
registerOnTouched() {
}
}
I believe the issue is that I'm not able to call my child component from my parent template.
Does anyone have any helpful advice for getting the chips component to add chips?
Thank you!
I've cleaned up your plunker and now I can get all the way to ngOnInit() in chips component without any error. Take it from here and let us know if you need help in setting up the logic. But before all that, I would like to ask you to refer to the docs on #Input() and #Ouput() decorators.
plunker