M.Mery
M.Mery

Reputation: 13

Displays/hide iframe on button click

I have an established app that I want to fork. I added .html, .component.ts, .module.ts as below. I think that my problem is simple, but I don't know how to code in Angular. I want to add a button that allows me to hide/how my iframes (button 1 : iframe 1 / button 2 : iframe 2). I only added one button. the button is displayed but when I click it I can see nothing. Could you please help me with this matter?

.module.ts :

import { NgModule } from '@angular/core';
    import { AppComponent } from './App.component';
    @NgModule({
        declarations: [
            AppComponent,
        ],
        imports:[],
        providers: [],
        entryComponents: [
           AppComponent
           ]
        })
    export class AppModule { }

.component.ts:

import { 
        Component,
        OnInit } from '@angular/core';
    @Component({
         selector: 'mui-App',
        templateUrl: 'App.component.html'
    })  
    export class AppComponent implements OnInit{ 
    public ngOnInit() {
        var x = document.getElementById("f1");
        if (x.style.display === "none") {
            x.style.display = "block";
       } else {
            x.style.display = "none";
        }
    }    
    }

.html

<button onclick="ngOnInit()">Show</button>
    <div id="f1">
        <iframe src="http://myiframe" WIDTH = 1850 HEIGHT= 970 >
        </iframe>
    </div>

    <div id="f2">
         <iframe src="http://myiframe2" WIDTH = 1850 HEIGHT= 970 >
         </iframe>
    </div>

Upvotes: 1

Views: 6944

Answers (2)

Anuradha Gunasekara
Anuradha Gunasekara

Reputation: 6983

Try this.

In your template.

    <button (click)="hideElement()">Show</button>
    <div #f1>
        <iframe src="http://myiframe" WIDTH = 1850 HEIGHT= 970 >
        </iframe>
    </div>

    <div #f2>
         <iframe src="http://myiframe2" WIDTH = 1850 HEIGHT= 970 >
         </iframe>
    </div>

In your component.

 import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'mui-App',
  templateUrl: 'App.component.html'
})

export class AppComponent implements AfterViewInit {

  @ViewChild('f1') f1: ElementRef;
  @ViewChild('f2') f2: ElementRef;

  public ngAfterViewInit(): void {
    this.hideElement()
  }

  public hideElement(): void {
    if (this.f1.nativeElement.style.display === "none") {
      this.f1.nativeElement.style.display = "block";
    } else {
      this.f1.nativeElement.style.display = "none";
    }
  }
}

Upvotes: 0

Nilesh Sutar
Nilesh Sutar

Reputation: 147

You can do this in your code...
In HTML

<button (click)="showMe =! showMe">Show</button>
<div *ngIf="showMe">
    <iframe src="http://myiframe" WIDTH = '1850' HEIGHT= '970' >
    </iframe>
</div>

<div *ngIf="!showMe">
     <iframe src="http://myiframe2" WIDTH = '1850' HEIGHT= '970' >
     </iframe>
</div>

In Typescript

public showMe = false;

Upvotes: 3

Related Questions