angular-editor icon indicating copy to clipboard operation
angular-editor copied to clipboard

How to get formControlName value from angular-editor ? Not able to get value of control if HTML code functionality is used with '<iframe>' tag. Mat-error shows in below attached screenshot

Open Deepak200981 opened this issue 6 years ago • 4 comments

Hi @kolkov , Is there anyway to get formControlName="description" from angular-editor. Below control value doesn't get if i use HTML code functionality. Client side mat-error shows.

It would be great if you suggested. Thank you. <angular-editor [config]="config" formControlName="description">

config: AngularEditorConfig = { editable: true, spellcheck: true, height: '15rem', minHeight: '5rem', placeholder: 'Enter embed code here...', translate: 'no', defaultParagraphSeparator: 'p', defaultFontName: 'Arial', toolbarHiddenButtons: [ ['bold'] ], customClasses: [ { name: "quote", class: "quote", }, { name: 'redText', class: 'redText' }, { name: "titleText", class: "titleText", tag: "h1", }, ] };

contentFormInit() { this.contentForm = this.fb.group({ name: ['', Validators.required], description: ['', Validators.required], content: [''], status: ['Active', Validators.required], skippable: [false], contentPosition: [Validators.required] });

}** angular-editor **

Deepak200981 avatar Oct 14 '20 06:10 Deepak200981

@kolkov Could you please suggest ?

Deepak200981 avatar Oct 15 '20 13:10 Deepak200981

Answer for this question in this article. It is works for me

OleksandrYatsiuk avatar Apr 15 '21 05:04 OleksandrYatsiuk

Thank you for your question!

Problem: Form Control Value Empty When Using <iframe>

The issue is that <iframe> tags are stripped by the DomSanitizer for security reasons.

Why This Happens

config: AngularEditorConfig = {
  sanitize: true  // Default - removes <iframe> tags!
};

When you paste or enter HTML code containing <iframe>, the sanitizer removes it as a potential XSS vector. This leaves your form control empty or with incomplete content.

Solution (from StackOverflow link in comments)

Option 1: Disable Sanitization (⚠️ Security Risk)

import { AngularEditorConfig } from '@kolkov/angular-editor';

config: AngularEditorConfig = {
  editable: true,
  spellcheck: true,
  height: '15rem',
  minHeight: '5rem',
  sanitize: false,  // ⚠️ Allows <iframe> but opens XSS vulnerability
  placeholder: 'Enter embed code here...',
  translate: 'no',
  defaultParagraphSeparator: 'p',
  defaultFontName: 'Arial',
  toolbarHiddenButtons: [
    ['bold']
  ]
};

⚠️ WARNING: Only use sanitize: false if:

  • You control all content
  • Content is from trusted sources
  • You understand the XSS risks

Option 2: Custom Sanitization (Safer)

Allow only specific iframe sources:

import { DomSanitizer, SecurityContext } from '@angular/platform-browser';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'safeIframe' })
export class SafeIframePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  
  transform(html: string): any {
    // Allow only YouTube and Vimeo iframes
    const allowedDomains = [
      'youtube.com',
      'youtube-nocookie.com',
      'vimeo.com'
    ];
    
    // Parse HTML
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    
    // Check all iframes
    doc.querySelectorAll('iframe').forEach((iframe: HTMLIFrameElement) => {
      const src = iframe.getAttribute('src');
      const isAllowed = allowedDomains.some(domain => src?.includes(domain));
      
      if (!isAllowed) {
        iframe.remove(); // Remove untrusted iframes
      }
    });
    
    return this.sanitizer.bypassSecurityTrustHtml(doc.body.innerHTML);
  }
}

Option 3: Store Raw HTML Separately

Use a hidden field to store the raw (unsanitized) HTML:

contentFormInit() {
  this.contentForm = this.fb.group({
    name: ['', Validators.required],
    description: ['', Validators.required],  // Sanitized version (for display)
    descriptionRaw: [''],  // Raw version (with iframes)
    content: [''],
    status: ['Active', Validators.required],
    skippable: [false],
    contentPosition: [Validators.required]
  });
}

// When user edits in HTML mode
onHtmlModeChange(html: string) {
  // Store both versions
  this.contentForm.patchValue({
    description: html,  // Will be sanitized by editor
    descriptionRaw: html  // Keep original with iframes
  });
}

// When saving to database
save() {
  const data = this.contentForm.value;
  // Use descriptionRaw for storage (contains iframes)
  this.api.save({
    ...data,
    description: data.descriptionRaw
  });
}

Option 4: Use YouTube/Vimeo Insert Feature

Instead of raw iframe code, use the built-in video insert:

config: AngularEditorConfig = {
  // ... other config
  toolbarHiddenButtons: [
    // Don't hide insertVideo
  ]
};

// Then users can click "Insert Video" and paste YouTube URL
// The editor handles the iframe safely

Validation Issue

The mat-error shows because the form control is empty. This happens when:

  1. User switches to HTML mode
  2. Pastes <iframe> code
  3. DomSanitizer strips the <iframe>
  4. Form control becomes empty
  5. Validation fails (required validator)

Complete Working Example

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AngularEditorConfig } from '@kolkov/angular-editor';

@Component({
  selector: 'app-content',
  template: `
    <form [formGroup]="contentForm">
      <angular-editor
        formControlName="description"
        [config]="config">
      </angular-editor>
      
      <mat-error *ngIf="contentForm.get('description').hasError('required')">
        Description is required
      </mat-error>
      
      <button (click)="save()">Save</button>
    </form>
  `
})
export class ContentComponent implements OnInit {
  contentForm: FormGroup;

  config: AngularEditorConfig = {
    editable: true,
    spellcheck: true,
    height: '15rem',
    minHeight: '5rem',
    placeholder: 'Enter content here...',
    translate: 'no',
    sanitize: false,  // ⚠️ Allow iframes (if content is trusted)
    defaultParagraphSeparator: 'p',
    defaultFontName: 'Arial',
    toolbarHiddenButtons: [
      ['bold']
    ]
  };

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.contentForm = this.fb.group({
      name: ['', Validators.required],
      description: ['', Validators.required],
      content: [''],
      status: ['Active', Validators.required],
      skippable: [false],
      contentPosition: [Validators.required]
    });
  }

  save() {
    if (this.contentForm.valid) {
      console.log('Form value:', this.contentForm.value);
      // Save to backend
    }
  }
}

Security Recommendation

If you need to support iframes:

  1. ✅ Use a whitelist of allowed domains
  2. ✅ Validate iframe sources server-side
  3. ✅ Use CSP (Content Security Policy) headers
  4. ✅ Consider using sandbox attribute on iframes
  5. ❌ Don't blindly disable sanitization

Related Issues

  • #580 - XSS security (consolidated tracking)
  • #308 - External CSS/JS interference
  • #339 - Style tag sanitization

Closing

Closing as this is a usage question with a solution provided in the StackOverflow link. The answer is to set sanitize: false in the config, understanding the security implications.

If you need help implementing secure iframe handling, please refer to the solutions above or open a new discussion!

kolkov avatar Nov 22 '25 15:11 kolkov

Closing as this is a sanitization issue with iframes. Set sanitize: false in config to allow iframes (⚠️ understand security risks). See detailed solutions above. Related to #580 (XSS security tracking).

kolkov avatar Nov 22 '25 15:11 kolkov