I want to embed Youtube videos in my ionic2 app I have used Youtube pipe and imported following:
import { DomSanitizer } from '#angular/platform-browser';
the youtube.ts contain following
constructor(private dom: DomSanitizer) {
}
transform(value, args) {
return this.dom.bypassSecurityTrustResourceUrl(value);
}
}
Also I have imported it in app.module.ts like this:
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
...
import{ YoutubePipe } from '../pipes/youtube/youtube';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
#NgModule({
declarations: [
MyApp,
HomePage,
...
YoutubePipe
],
In my .html file I have written this:
<iframe width="560" Cannot GET /uri.vurl%20%7C%20youtube
height="315" src="uri.vurl | youtube" frameborder="0" allowfullscreen></iframe>
It giving me like this on the output screen:
Cannot GET /uri.vurl%20%7C%20youtube
What should I do anyone please help.
First, you need to import DomSanitizer in your .ts file like this:
import { DomSanitizer } from '#angular/platform-browser';
Next, declare a variable in your constructor
constructor(..., private sanitizer: DomSanitizer) {}
If you are display a single video which you already have the uri, you can declare an instance variable and pass in the uri like this:
this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl("https://....")
Now, in your .html file, do this:
<iframe [src]="videoUrl" frameborder="0" width="100%" height="155" allowfullscreen></iframe>
Hope this helps.
Related
I have installed angular material and then imported into my app-module
Now I want to use a selector of employees so I have this template in my component
<mat-form-field appearance="fill">
<mat-label>Empleado</mat-label>
<mat-select [(value)]="empleadoSeleccionado">
<mat-option [value]="empleado.empleadoID" *ngFor="let empleado of listaEmpleados">{{empleado.nombre}}</mat-option>
</mat-select>
In material module I have imported MatSelectModule and MatFormFielModule
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { MatSelectModule } from '#angular/material/select';
import { MatFormFieldModule } from '#angular/material/form-field';
#NgModule({
declarations: [],
imports: [
CommonModule,
MatSelectModule,
MatFormFieldModule,
]
})
export class MaterialModule { }
But I get always this same error NG8001: 'mat-form-field' is not a known element:
Any idea, please?
Thanks
The error was in Material Module where I need export the array not import
Thanks
I've been trying to get ContentChild with Directive working in a demo/example and I keep running into the directive not working. No errors being thrown. I've replicated the scenario on StackBlitz and I'm getting the same problem: https://stackblitz.com/edit/angular-contentchild-directive-etktcd
Why am I still getting "undefined" for the child input?
Here is the Directive:
import { Component, Directive, Input, ContentChild, OnInit, OnDestroy, forwardRef, AfterContentInit} from '#angular/core';
import { AbstractControl } from '#angular/forms';
import { FocusDirective } from '../directive/focus.directive';
#Component({
selector: 'field-validation',
template: `
<ng-content></ng-content>
`
})
export class FieldValidationComponent implements OnInit, AfterContentInit {
#ContentChild(FocusDirective) input: FocusDirective;
ngOnInit(): void {
console.log("ngOnInit::input is: ", this.input);
// this.input.focusChange.subscribe((focus) => {
// this.updateAttributes();
// });
}
ngAfterContentInit(): void {
console.log("ngAfterContentInit::input is: ", this.input);
}
}
Here is the child Component:
import { Component, Directive, Input, ContentChild, OnInit, OnDestroy,
forwardRef, AfterContentInit} from '#angular/core';
import { AbstractControl } from '#angular/forms';
import { FocusDirective } from '../directive/focus.directive';
#Component({
selector: 'field-validation',
template: `
<ng-content></ng-content>
`
})
export class FieldValidationComponent implements OnInit, AfterContentInit {
#ContentChild(FocusDirective) input: FocusDirective;
ngOnInit(): void {
console.log("ngOnInit::input is: ", this.input);
// this.input.focusChange.subscribe((focus) => {
// this.updateAttributes();
// });
}
ngAfterContentInit(): void {
console.log("ngAfterContentInit::input is: ", this.input);
}
}
Here is the HTML in the parent app:
<form [formGroup]="testForm">
<field-validation>
<input type="text" placeholder="0.00">
</field-validation>
<div>
<button type="submit">FAKE SUBMIT</button>
</div>
</form>
Please add the FocusDirective class to declaration property of AppModule, as shown below.
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { FieldValidationComponent } from './child-component/field-validation.component';
import { RxReactiveFormsModule } from '#rxweb/reactive-form-validators'
import { FocusDirective } from './directive/focus.directive';
#NgModule({
imports: [ BrowserModule, ReactiveFormsModule, RxReactiveFormsModule],
declarations: [ AppComponent, HelloComponent, FieldValidationComponent, FocusDirective],
bootstrap: [ AppComponent ]
})
export class AppModule { }
I'm new to Angular2 and have many questions.
I have some controllers that I wrote in AngularJS that I now want to convert to Angular2 components.
I would like to pass JSON data to the component and use in the template. In AngularJS I used ng-init to do this.
I have tried initialising the component in the ASP.NET MVC view with:
<review [reviewJson]="#Newtonsoft.Json.JsonConvert.SerializeObject(Model.CustomerReviews)"></review>
The component looks like this:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'review',
template: `
<div id="reviews-wrapper" class="row">
<div class="item col-sm-4 col-xs-6" *ngFor="let review of reviewJson">
<div class="review-card">
<div class="review-image"><img [src]="review.Image"/></div>
<div class="review-name">review.Name</div>
<div class="review-text">review.Text</div>
</div>
</div>
</div>
`,
providers: []
})
export class ReviewComponent implements OnInit {
#Input() reviewJson: any;
constructor() {
}
ngOnInit() {
console.log(this.reviewJson);
}
}
The app.module file where I declare the review component looks like this:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule } from '#angular/http';
import { ReviewComponent } from './review.component';
#NgModule({
imports: [
BrowserModule,
HttpModule
],
declarations: [
ReviewComponent
],
bootstrap: [ReviewComponent],
providers: [
]
})
export class AppModule { }
The console.log(this.reviewJson) is showing undefined when I load the page so obviously I'm doing something completely wrong.
Any help appreciated.
You cannot directly bind the MVC models into the angular template - fetch the data as JSON using service and then bind the value to it's #Input decorator
Hope this helps - happy coding :)
I use CoreUI (angular 6 version) in order to create a simple panel.
I need to have a datepicker, but cannot manage to find how to do it.
Angular material might be a nice solution, but I don manage to include it - looks like there are some basic conflicts.
Any simple solution?
you install a date-time-picker package:
npm install --save angular-bootstrap-datetimepicker bootstrap moment open-iconic
// added the following to app.module.ts
import { AppComponent } from './app.component';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { NgModule } from '#angular/core';
import { DlDateTimePickerDateModule } from 'angular-bootstrap-datetimepicker';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
DlDateTimePickerDateModule,
],
providers: [FormsModule],
bootstrap: [AppComponent]
})
export class AppModule { }
//added the following to app.component.html
<dl-date-time-picker
startView="day"
maxView="year"
minView="minute"
minuteStep="5"
[(ngModel)]="selectedDate"
>
</dl-date-time-picker>
// added following to ./src/styles.css
#import '~bootstrap/dist/css/bootstrap.min.css';
#import '~open-iconic/font/css/open-iconic-bootstrap.css';
You can add ngx-bootstrap, it has BootStrap datepicker compatible with Bootstrap V3 & V4.
You can check it here: https://valor-software.com/ngx-bootstrap/#/datepicker
To install ngx-bootstrap, run this command
ng add ngx-bootstrap --component datepicker
Then add the following code to your AppModule
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
#NgModule({
imports: [BsDatepickerModule.forRoot(),...]
})
export class AppModule(){}
Sample usage (at the template):
<input type="text" placeholder="Datepicker" class="form-control" bsDatepicker>
Calling Youtube API in
ngOnInit(){
var finalURL = "https://www.googleapis.com/youtube/v3/search?key="+this.api+"&channelId="+this.chanId+"&part=snippet,id&order=date&maxResults="+this.result+""
console.log(finalURL);
this.obser$ = this.http.get(finalURL).subscribe(response=>{
console.log(response);
let ytresults= response.json();
console.log(ytresults);
ytresults.items.forEach(obj => {
console.log(obj.id.videoId);
this.ytvideolist.push(obj.id.videoId);
});
console.log(this.ytvideolist);
}
trying here to make the video url sanitized
<li *ngFor= "let id of ytvideolist">
<iframe [src]="getEmbedUrl(id)" frameborder="0" allowfullscreen></iframe>
</li>
Using DOM sanitizer in the function getEmbedUrl(id)
getEmbedUrl(id){
console.log(id);
return this.sanitizer.bypassSecurityTrustResourceUrl('https://youtube.com/embed/'+id);
}
Everything is working fine videos are getting fetched but part of the DOM continuously getting refreshed. I tried to do unsubscribe at all the component lifecycle hooks. But If I unsubscribe I won't fetch any results only. Is there any other work-around or am I missing some thing here!
Solved the problem using pipe
import { Pipe, PipeTransform } from '#angular/core';
import {DomSanitizer, SafeResourceUrl} from "#angular/platform-browser";
#Pipe({
name: 'youtubeSafeUrl'
})
export class YoutubePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer){
}
transform(videoId: string): SafeResourceUrl {
return this.sanitizer.bypassSecurityTrustResourceUrl(
`https://www.youtube.com/embed/${videoId}`);
}
}
Inside html did something like this
<div *ngFor= "let videoId of ytvideolist" class="shadow1">
<iframe [src]="videoId | youtubeSafeUrl" frameborder="0" allowfullscreen></iframe>
</div>
I was guessing problem with subscription. anyhow it resolved!
I hope it helps somebody.